Search code examples
c++stringc++11istream-iterator

Using istream_iterator to read strings


I don't understand exactly how reading a string via iterators is different from reading it directly. To exemplify, consider the code below:

#include <iostream>
#include <string>
#include <iterator>

using namespace std;

int main() 
{
    string str{istream_iterator<char>(cin),{}};
    cout << str << endl;

    string str1;
    cin >> str1;
    cout << str1 << endl;
}

It is obvious what it does, it reads str using an istream_iterator, and reads str1 via traditional method. I have 2 questions:

  1. The only way of ending the reading via string iterators is to send a CTRL+D (Unix), which also terminates the program, so the second part is not executed. Is there any way around this?
  2. When reading with iterators, it doesn't matter if I input whitespaces (space, \t, \n), the iterator keeps reading. Why is this behaviour different from the one when reading directly via cin >>?

Solution

  • I don't understand exactly how reading a string via iterators is different from reading it directly.

    The difference in your example is that the first reads the entire stream, while the second reads a single word (until the first space).

    More generally, iterators can be used to fill other containers (e.g. using istream_iterator<int> to fill vector<int>), or passed directly to algorithms that work with forward iterators.

    The only way of ending the reading via string iterators is to send a CTRL+D (Unix), which also terminates the program

    It doesn't terminate the program, it just closes the input stream. But you won't be able to read anything else from the input after doing that; as it stands, your program doesn't make sense since it tries to read beyond the end of cin.

    When reading with iterators, it doesn't matter if I input whitespaces (space, \t, \n), the iterator keeps reading. Why is this behaviour different from the one when reading directly via cin >>?

    Because that's how >> is defined to work with strings.