How to iterate for each character in a Std::istream?

Asked

Viewed 196 times

2

1 answer

2

I believe you must 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 in which 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;
}
  • And how I would do that without the z, but rather check when Cin was done?

  • 2

    @Lucashenrique You can use Std::istream_iterator the same way as any other iterator. To scroll through all of the input characters, you will need the start iterator, as shown in the answer, and the end iterator, which is simply a Std::istream_iterator built without passing, in this case, Std::Cin. Having the two iterators just compare them to each iteration and when they are different means that you have read all.

  • @DBX8 I already knew this technique; however, Std::Cin goes into a loop, and I don’t know how to break it. How should I get the input done just once?

  • It must also be from your awareness that example 2 does not give output. (Mingw 4.8.1)

  • Still not working.

  • 1

    As a matter of fact, I can only get into the computer now. And it’s working. But think: if I give a proper example for creating a string, how would I use a string???

  • 1

    I don’t understand your last question, @Lucashenrique...

  • @Sunstreaker thinks: if I am implementing a string, how would I use a string?

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.