从 istream 复制永远不会停止
这段代码无限运行:
copy(istream_iterator<char>(cin), istream_iterator<char>(), back_inserter(buff));
我所期望的行为是当我按 Enter 时它将停止。
然而事实并非如此。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您正在键盘上输入内容。
Enter 键并不表示流的结束。从cin的角度来看,这只是另一个角色。您需要提交 EOF 才能实现此目的(Windows 上为 Ctrl+Z、Enter 以及 Ctrl+ D(Unix/Mac 上)。
顺便说一句,这不是从控制台读取字符的常用方法。它的效率非常低(
istream_iterator
为每个字符调用operator>>
)并且会对空格产生错误行为。要读取一行数据输入,请改用getline
。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
callsoperator>>
for each character) and will misbehave with whitespace. To read a line of data entry, usegetline
instead.