How to iterate through each character in a std :: istream?

2

In std::string , the allocation is done like this; in chunks of 128 characters note . It takes each input character and places it by std::string::push_back . How can I do it?

Note - link

    
asked by anonymous 24.05.2014 / 04:54

1 answer

2

I believe you should be looking for istream_iterator .

Consider a simple example:

#include <iostream>
#include <iterator>

using namespace std;

int main()
{
  istream_iterator<char> iit(cin);

  do 
  {
      cout << *iit;
      iit++;
  } 
  while (*iit != 'z'); 

  return 0;
}

If you enter a sentence where the last character is the letter z , for example FooBarz , cout will only show FooBar disregarding z .

Another example, now using vectors , corrected:

#include <iostream>
#include <iterator>
#include <vector>

int main()
{
    std::vector <std::string> v;
    std::istream_iterator<std::string> iit(std::cin);
    v.push_back(*iit);

    for ( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ )
    std::cout << *i << std::endl;

    return 0;
}
    
24.05.2014 / 17:15