istream_iterator 在读取字符时忽略 EOF (Ctrl+D)
我正在尝试使用 istream_iterator 从 cin 读取字符。我读到按 Ctrl+D 会发送一个 EOF
字符来结束输入流。不幸的是,它出了点问题。这是我的代码:
#include <iterator>
int main()
{
using namespace std;
istream_iterator<char> it(cin), eos;
while (it != eos) clog << *(it++);
}
我正在运行它并输入:as df
,然后按Ctrl+D。 它仅输出 asd
而没有最后一个 f
,然后挂起等待输入。当我输入 gh
并再次按 Ctrl+D 时,它最后会打印剩余的 f
和 < code>g 来自下一个输入,但同样没有最后一个 h
。当我最终按下 Ctrl+D 而不输入任何内容时,它会打印剩余的 h
并退出。
我希望它读取 asdf
并退出,因为我已经在第一个序列末尾按下了 Ctrl+D 。
为什么获取EOF
后还在等待输入?
为什么它不打印 EOF
之前读取的最后一个字符?
为什么只有当我按 Ctrl+D 且之前没有输入任何内容时它才会退出?
这个循环需要如何改变才能使其按照我期望的方式运行? (即在输入中获取 Ctrl+D 序列后立即停止阅读,无论我之前是否输入过任何内容,并向上读取所有个字符到EOF
)。
I'm trying to use istream_iterator
for reading characters from cin
. I've read that pressing Ctrl+D sends an EOF
character which ends the input stream. Unfortunately, something is going wrong with it. Here's my code:
#include <iterator>
int main()
{
using namespace std;
istream_iterator<char> it(cin), eos;
while (it != eos) clog << *(it++);
}
I'm running it and typing: as df
, then pressing Ctrl+D.
It outputs only asd
without the last f
and then hangs waiting for input. When I type gh
and press Ctrl+D again, it prints the remaining f
at last, and the g
from next input, but again without the last h
. And when I finally press Ctrl+D without typing anything, it prints the remaining h
and exits.
I expected it to read asdf
and exit, since I already pressed Ctrl+D at the end of this first sequence.
Why is it still waiting for input after getting EOF
?
Why it doesn't print the last character read before EOF
?
And why it exits only when I press Ctrl+D without typing anything before?
How does this loop need to change to make it behave in the way I expect? (i.e. stop reading immediately after getting Ctrl+D sequence in the input, no matter I typed anything before or not, and reading all characters up to the EOF
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
输入迭代器需要特别小心。以这种方式重写循环,其行为将变得与任何其他字符输入循环类似:
这将解决“为什么它不打印最后一个字符”
PS:至于行中间的 EOF,它是 < a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap11.html#tag_11_01_09" rel="nofollow">POSIX 强制行为:
Input iterators require special care. Rewrite your loop this way and the behavior will become similar to any other character input loop:
That will take care of "Why it doesn't print the last character"
PS: as for EOF in the middle of the line, it is the POSIX-mandated behavior:
在类 Unix 系统上,键入 Ctrl+D 仅在行首触发文件结束条件(即,在键入 Enter< /kbd>。要在行中间触发文件结束条件,请键入 Ctrl+D 两次。
On Unix-like systems, typing Ctrl+D triggers an end-of-file condition only at the beginning of a line (i.e., immediately after typing Enter. To trigger an end-of-file condition in the middle of a line, type Ctrl+D twice.