从 istream 复制永远不会停止

发布于 2024-08-31 19:36:43 字数 199 浏览 2 评论 0原文

这段代码无限运行:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月野兔 2024-09-07 19:36:43

我假设您正在键盘上输入内容。

Enter 键并不表示流的结束。从cin的角度来看,这只是另一个角色。您需要提交 EOF 才能实现此目的(Windows 上为 Ctrl+ZEnter 以及 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 calls operator>> for each character) and will misbehave with whitespace. To read a line of data entry, use getline instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文