istream_iterator invokes reading from the keyboard by just defining it!!

Sep 1, 2023 at 11:55pm
Hi,

The following code opens for reading from the keyboard instead of waiting for the vector: (this does not occur if the istream is an ifstream - associated with a file)


1
2
3
istream_iterator<string> in {cin }; // this reads the keyboard immediately why??
istream_iterator<string> eos;
vector<string> vec{ in, eos };     // this is where I expect reading the keyboard!! 


Sep 2, 2023 at 5:09am
The actual read operation is performed when the iterator is incremented, not when it is dereferenced.
The first object is read when the iterator is constructed.
Dereferencing only returns a copy of the most recently read object.
https://en.cppreference.com/w/cpp/iterator/istream_iterator
Sep 2, 2023 at 4:01pm
This activates reading but I can never close the input unless I write Ctrl-Z or Ctrl-C... why doesn't it end reading when I press ENTER?


1
2
vector<string> vec{ istream_iterator<string> {cin }, istream_iterator<string> {}};
bool eof = cin.eof();  // this return true 


must do cin.clear() in order to continue reading from cin... Why necessary?

Sep 2, 2023 at 4:16pm
this line of reading does not end when pressed ENTER, why?

 
vector<string> vec{ istream_iterator<string> {cin }, istream_iterator<string> {}}



Sep 2, 2023 at 4:42pm
Pressing enter does not end the stream.
Sep 2, 2023 at 4:52pm
Then how come ENTER terminates input for this instruction?

 
istream_iterator<string> in {cin };




Try it out please
Last edited on Sep 2, 2023 at 4:57pm
Sep 2, 2023 at 5:43pm
Because of what JLBorges posted.
The first object is read when the iterator is constructed.

Once it has read that one first string token the code continues.
Last edited on Sep 2, 2023 at 5:43pm
Sep 3, 2023 at 4:09pm
Pressing enter does not end the stream.


Correct. This iterates the stream until eof is found (istream_iterator<string> {}). For Windows cin, eof is ctrl-z. So to terminate the input enter ctrl-z on a line by itself.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
	vector<string> vec{ istream_iterator<string> {cin }, istream_iterator<string> {}};

	for (const auto& v : vec)
		cout << v << '\n';
}


This will generate vec from the input with a new element inserted for every white space in the input. The input is terminated with ctrl-z


foobar barfoo
^Z
foobar
barfoo


foorbar barfoo is entered. Then ctrl-Z to terminate. Then the contents of vec are displayed.
Topic archived. No new replies allowed.