从重定向到 STDIN 的文件中检测 C++ 中的 EOF [英] Detecting EOF in C++ from a file redirected to STDIN

查看:25
本文介绍了从重定向到 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:

  1. cin 检查任何故障位(BADBIT、FAILBIT)
  2. cin 报告没有问题,因为尚未从文件中读取任何内容.
  3. getline 被调用以检测文件结尾,设置 EOF 位和 FAILBIT.
  4. 循环从 1 开始再次执行,除了这次它退出.
  1. cin is checked for any of the failure bits (BADBIT, FAILBIT)
  2. cin reports no problem because nothing has yet been read from the file.
  3. getline is called which detects end of file, setting the EOF bit and FAILBIT.
  4. 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆