.eof()循环不工作 [英] .eof() loop not working
问题描述
我试图从一个文件中读取数字,并将它们放入数组。现在当我运行程序打印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标志,停止操作,直到状态被清除。如果你检查坏
,它会去,直到它无法解析,但会错误在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.
这篇关于.eof()循环不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!