How to use istream_iterator to read input from cin twice?

O

oliu321

I have the following code:

vector<int> A, B;
copy(istream_iterator<int>(cin), istream_iterator<int>(),
back_inserter(A));
copy(istream_iterator<int>(cin), istream_iterator<int>(),
back_inserter(B));

If I input the following

1 2 3 4 a <CR>

then I can get A as 1,2,3,4 which is OK, but then the second copy
won't read anything and the B becomes empty.

I can see that cin has bad bit set to true after the first copy which
it should be. But even after I called a cin.clear() before the second
copy, I still couldn't get the program to try to read my second line
of input into B. I guess somewhat you should tweak the cin to force
the second copy work. But how?

Thanks
Ou
 
D

David Harmon

On 22 Mar 2007 13:49:48 -0700 in comp.lang.c++, (e-mail address removed) wrote,
I can see that cin has bad bit set to true after the first copy which
it should be. But even after I called a cin.clear() before the second
copy, I still couldn't get the program to try to read my second line
of input into B.

Even after you call cin.clear(), the funky character is still waiting to
be read in the input stream. You need to do something to read it. My
favorite would probably be
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
 
O

oliu321

On 22 Mar 2007 13:49:48 -0700 in comp.lang.c++, (e-mail address removed) wrote,


Even after you call cin.clear(), the funky character is still waiting to
be read in the input stream. You need to do something to read it. My
favorite would probably be
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

It works great, thanks a lot.
 
O

oliu321

It works great, thanks a lot.

By the way, for those who are interested in this post, here is a
working code:

vector<int> A, B;
// Type 1 2 3 4 a <CR>
copy(istream_iterator<int>(cin), istream_iterator<int>(),
back_inserter(A));
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// Type 4 5 6 7 b <CR>
copy(istream_iterator<int>(cin), istream_iterator<int>(),
back_inserter(B));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top