开发者

Copying from istream never stops

开发者 https://www.devze.com 2022-12-29 10:34 出处:网络
This bit of code runs infinitely: copy(istream_iterator开发者_如何学运维<char>(cin), istream_iterator<char>(), back_inserter(buff));

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消