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 开始再次执行,除了这次它退出.
cinis checked for any of the failure bits (BADBIT, FAILBIT)cinreports no problem because nothing has yet been read from the file.getlineis 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
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
