从重定向到 STDIN 的文件中检测 C++ 中的 EOF
执行命令:
./program < input.txt
使用以下代码检查:
string input;
while(cin) {
getline(cin, input);
}
上面的代码似乎在输入为空的地方生成了一个额外的 getline()
调用.不管 input.txt 的最后一行是否有
,都会发生这种情况.
The above code seems to generate an extra getline()
call where input is empty. This happens regardless of whether or not there's a
on the last line of input.txt.
推荐答案
@Jacob 有正确的解决方案,但由于某种原因删除了他的答案.这是您的循环中发生的事情:
@Jacob had the correct solution but deleted his answer for some reason. Here's what's going on in your loop:
cin
检查任何故障位(BADBIT、FAILBIT)cin
报告没有问题,因为尚未从文件中读取任何内容.getline
被调用以检测文件结尾,设置 EOF 位和 FAILBIT.- 循环从 1 开始再次执行,除了这次它退出.
cin
is checked for any of the failure bits (BADBIT, FAILBIT)cin
reports no problem because nothing has yet been read from the file.getline
is called which detects end of file, setting the EOF bit and FAILBIT.- Loop executes again from 1, except this time it exits.
你需要做这样的事情:
std::string input;
while(std::getline(std::cin, input))
{
//Have your way with the input.
}
相关文章