c++ - istream_iterator 在读取字符时忽略 EOF (Ctrl+D)

标签 c++ eof cin istream istream-iterator

我正在尝试使用 istream_iteratorcin 中读取字符。我读到按下 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,并且 g 来自下一个输入,但同样没有最后一个 h。当我最终按下 Ctrl+D 而没有输入任何内容时,它会打印剩余的 h 并退出。

我预计它会读取 asdf 并退出,因为我已经在第一个序列的末尾按下了 Ctrl+D

为什么得到EOF后还在等待输入?
为什么它不打印在 EOF 之前读取的最后一个字符?
为什么它只在我按下 Ctrl+D 之前没有输入任何内容时退出?
这个循环需要如何改变才能使它按照我期望的方式运行? (即在输入 Ctrl+D 序列后立即停止阅读,无论我之前是否输入任何内容,并阅读所有字符到 EOF)。

最佳答案

输入迭代器需要特别小心。以这种方式重写您的循环,行为将变得类似于任何其他字符输入循环:

while (it != eos)
{
    clog << *it;
    it++;
}

这将解决“为什么它不打印最后一个字符”

PS:至于行中间的EOF,是POSIX-mandated behavior :

When received, all the bytes waiting to be read are immediately passed to the process without waiting for a newline, and the EOF is discarded. Thus, if there are no bytes waiting (that is, the EOF occurred at the beginning of a line), a byte count of zero shall be returned from the read(), representing an end-of-file indication.

关于c++ - istream_iterator 在读取字符时忽略 EOF (Ctrl+D),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7338071/

相关文章:

c++ - 具有可变多维 initializer_list 的构造函数

c++ - 是否有任何工具支持 C++ 基于检查点的内存使用分析

c++ - 为什么在读取时发现 eof 时会设置故障位?

python - 在 python 中,如何检查标准输入流 (sys.stdin) 的结尾并对此做一些特殊的事情

C++ 用户输入一个字符,变量保持为0

c++ - 这种重载 operator new 有什么问题吗?

c++ - 如何在 native 事件中创建 OpenGL ES 2 上下文?

c++ - getline 并立即测试 EOF

c++ - 为什么 std::noskipws 不起作用,或者它应该做什么?

C++ getline cin 问题