Detecting EOF in C++ from a file redirected to STDIN(从重定向到 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.
}
这篇关于从重定向到 STDIN 的文件中检测 C++ 中的 EOF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从重定向到 STDIN 的文件中检测 C++ 中的 EOF


- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- Stroustrup 的 Simple_window.h 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 从python回调到c++的选项 2022-11-16