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!!
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
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>
usingnamespace std;
int main() {
vector<string> vec{ istream_iterator<string> {cin }, istream_iterator<string> {}};
for (constauto& 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.