.eof() loop not working(.eof() 循环不起作用)
问题描述
我正在尝试从文件中读取数字并将它们放入数组中.现在,当我运行该程序时,它会打印 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.
这篇关于.eof() 循环不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:.eof() 循环不起作用
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01