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

查看:156
本文介绍了从重定向到STDIN的文件中检测C ++中的EOF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行命令:

  ./ program< input.txt 

使用以下代码检查:

 字符串输入; 
while(cin){
getline(cin,input);
}

上面的代码似乎生成一个额外的 getline )调用where输入为空。无论是否在input.txt的最后一行有 \\\
,都会发生这种情况。

解决方案

@Jacob有正确的解决方案,但由于某种原因删除了他的答案。下面是你的循环中发生了什么:


  1. cin 失败位(BADBIT,FAILBIT)

  2. 报告没有问题,因为尚未从文件读取任何内容。
  3. $调用b $ b
  4. getline ,检测文件结束,设置EOF位和FAILBIT。


  5. $ b

      std :: string input; 
    while(std :: getline(std :: cin,input))
    {
    //让你的输入方式。
    }


    Executing the command:

    ./program < input.txt
    

    with the following code checking:

    string input;
    while(cin) {
      getline(cin, input);
    }
    

    The above code seems to generate an extra getline() call where input is empty. This happens regardless of whether or not there's a \n on the last line of input.txt.

    解决方案

    @Jacob had the correct solution but deleted his answer for some reason. Here's what's going on in your loop:

    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.

    You need to do something like this instead:

    std::string input;
    while(std::getline(std::cin, input))
    {
         //Have your way with the input.
    }
    

    这篇关于从重定向到STDIN的文件中检测C ++中的EOF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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