views:

63

answers:

1

This bit of code runs infinitely:

copy(istream_iterator<char>(cin), istream_iterator<char>(), back_inserter(buff));

The behavior I was expecting is that it will stop when I press enter.
However it doesn't.
buff is a vector of chars.

+2  A: 

I assume you are typing stuff in at the keyboard.

The enter key doesn't signify the end of the stream. It's just another character from cin's perspective. You need to submit EOF to achieve this (Ctrl+Z, Enter on Windows and Ctrl+D on Unix/Mac).

Incidentally, this isn't the usual way to read characters from the console. It is very inefficient (istream_iterator calls operator>> for each character) and will misbehave with whitespace. To read a line of data entry, use getline instead.

Marcelo Cantos
So basically what you are saying is that I am coding this wrong?
the_drow
Yes; I've amended the question to reflect what I think you are trying to accomplish.
Marcelo Cantos
I tried getline but it doesn't work with a vector.It works when I cin >> tempstring; and then copy it into the vector however it is very inefficient in my opinion.
the_drow
You are supposed to use it with a std::string, not a vector. Copying to a vector is at least ten million times faster than your typing speed, so efficiency is hardly an issue. In any case, you should be able to do pretty much anything with a string that you can with a vector.
Marcelo Cantos
BTW, `cin >> tempstring` doesn't read lines, it reads until the next whitespace.
Marcelo Cantos
For better performance, `istreambuf_iterator<char>(cin)` could be used too. That's faster since it won't do formatting and all that.
Johannes Schaub - litb
@Johannes Schaub - litb: Could you demonstrate how such code will look like?
the_drow
@the_drow exactly like your code just with the iterator names changed :)
Johannes Schaub - litb
Thank you very much :)
the_drow