I am new to C++, sorry if this is a silly question. I cannot seem to figure out why this does not work. It copies into the first vector, and seems to skip past the second copy call.
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main ()
{
vector<int> first;
vector<int> second;
copy(istream_iterator<int>(cin),istream_iterator<int>(),back_inserter(first));
cin.clear();
copy(istream_iterator<int>(cin),istream_iterator<int>(),back_inserter(second));
return 0;
}
I want to use the copy function to read istream_iterator input into any number of vectors(one call to copy per vector). In other words: I want to be able to enter "1 2 3 4 5 ctrl+d" into the console and have 1,2,3,4,5 entered into the first vector. Then enter "6 7 8 9 10 ctrl+d" into the console and have 6,7,8,9,10 entered into the second vector.
The problem is that after I enter some input into the first vector and press control+d the istream_iterator for cin remains equal to istream_iterator(), regardless of cin's fail state. This causes every subsequent call to "copy" to fail (because istream_iteratorcin is already equal to istream_iterator() which the program interprets as eof). So my question is: What do I need to do to "reset" the iterator along with the cin stream? cin.clear() is indeed clearing all the fail bits. However the istream_iterator(cin) is still equal to istream_iterator() regardless. From what I understand, istream_iterators that are bound to a stream should only be equal to the default istream_iterator value when the stream is in a fail state. What am I missing?
How it should workandwhat is not working. - Alok Save