我正在尝试使用 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
,并且 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/