.eof() 循环不起作用

2021-12-26 00:00:00 loops while-loop c++

我正在尝试从文件中读取数字并将它们放入数组中.现在,当我运行该程序时,它会打印 8 个数字,然后该行结束并打印相同的 8 个数字.这是一个永无止境的循环.我做错了什么?

I'm trying to read in numbers from a file and putting them into an array. Right now when I run the program it prints 8 numbers, then the line ends and prints the same 8 numbers. It's in a never ending loop. What am I doing wrong?

#include <iostream>                                                             
#include <fstream>                                                              
using namespace std;                                                            

int main()                                                                      
{                                                                               
  int num;                                                                      
  ifstream infile;                                                              
  infile.open("euler8Nums.txt");                                                
    infile >> num;//must attempt to read info prior to an eof() test            
    while(!infile.eof()){                                                       
      cout << num << endl;                                                      
      infile >> num;                                                            
    }                                                                           
    infile.close();                                                             
    return 0;                                                                   
}  

推荐答案

一般来说,不要使用 .eof().bad().只需检查流本身的状态

In general, don't use .eof() or .bad(). Just check the state of the stream itself

while (infile >> num)
    cout << num << endl;

如果流解析输入失败,则不会设置 eof 标志,然后流将停止运行,直到状态被清除.如果您改为检查 bad,它将一直持续到解析失败,但会在 EOF 处出错.所以只需检查流是否仍然是 .good(),(当它处于 while 循环时这是隐式的).

The eof flag will not be set if the stream fails to parse an input, and then the stream will cease to operate until the state is cleared. If you checked bad instead, it would go until it failed to parse, but would bug out at the EOF. So just check if the stream is still .good(), (which is implicit when it's in a while loop).

在您的情况下,这是一个无限循环,因为文件没有打开,然后您正在尝试读取数字,但是读取什么都不做,因为文件未打开不开.因此它永远不会读取 eof,从而无限循环.

In your case, it's an infinite loop because the file did not open and then you are attempting to read numbers, but the reading is doing nothing because the file isn't open. Thus it never reads the eof, thus infinite loop.

相关文章