Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 >>?
like image 517
vsoftco Avatar asked May 17 '26 10:05

vsoftco


2 Answers

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.

like image 165
Mike Seymour Avatar answered May 19 '26 23:05

Mike Seymour


  1. If you've reached the end of the stream there can't be anything more to read.

  2. The end iterator provided in the range constructor represents the end of the input. When an invalid character or the end of the stream is met (EOF is found), the start iterator will equal the end iterator, and that's how it stops. Stream iterators do discard whitespace so if you print your string it should contain no whitespace.

    The second extraction is formatted uses whitespace to delimit input, and that is why only one word is read.

like image 41
David G Avatar answered May 19 '26 22:05

David G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!