Using istream_iterator to read strings

I don't understand exactly how reading a string using iterators is different from reading directly. To illustrate this, 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;
}

      

Obviously what he does, he reads str

with istream_iterator

and reads str1

with the traditional method. I have 2 questions:

  • The only way to stop reading with string iterators is to send CTRL+D

    (Unix), which also exits the program, so the second part is not executed. Is there a way to get around this?
  • When reading with iterators, it doesn't matter, typing in spaces (space, \ t, \ n) the iterator keeps reading. Why is this behavior different from this when reading directly through cin >>

    ?
+3


source to share


2 answers


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

The difference in your example is that the former reads the entire stream and the latter reads one word (up to the first space).

More generally, iterators can be used to fill other containers (for example, using istream_iterator<int>

to fill vector<int>

), or passed directly to algorithms that work with forward iterators.

The only way to stop reading with line iterators is to send CTRL+D

(Unix), which also terminates the program



It doesn't terminate the program, it just closes the input stream. But after that, you won't be able to read anything else from the input; as it is, your program is meaningless as it tries to read outside cin

.

When reading with iterators, it doesn't matter, typing in spaces (space, \ t, \ n) the iterator continues reading. Why is this behavior different from this when reading directly through cin >>

?

Because as >>

defined to work with strings.

+3


source


  • Once you've reached the end of the stream, there is nothing more to read.

  • The end iterator provided in the range constructor represents the end of the input. When an invalid character or end of stream is encountered (found EOF

    ), the start iterator will be equal to the end of the end iterator and how it stops. Stream iterators strip off spaces, so if you are printing a string, it must not contain spaces.

    The second extraction is formatted using spaces to delimit the input and therefore only one word is read.



+3


source







All Articles