gpt4 book ai didi

c++ - 从文件中读取整数时无限循环

转载 作者:行者123 更新时间:2023-11-30 05:40:30 25 4
gpt4 key购买 nike

我有两个文件。 main.cpp :

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
ifstream file;
file.open("file.txt");

if (!file.good()) {
cout << "Error." << endl;
return 1;
}

int n;
while (!file.eof()) {
file.clear();

file >> n;
if (!file.good() && !file.bad()) {
continue;
} else {
cout << "Hardware error." << endl;
break;
}
cout << n << endl;
}

file.close();

return 0;
}

和文件.txt:

a 1 2 321b9 ac.de ef#@g 5 #3

我只想从此文件中读取整数并将它们写到控制台。当文件只包含整数时,程序运行良好,但当它包含任何无效字符时,我就会陷入无限循环。我该如何解决?

最佳答案

循环是因为流没有提取非整数的字符。在尝试读取另一个整数之前,您需要提取它。

可能只需要一个小的调整;

// on a failed read...
file.clear();
char dummy;
file >> dummy;
continue;

关于使用 while (!file.eof()) 的附注;一般不建议这样做。关于这个问题,SO上有几个Q&A。

关于c++ - 从文件中读取整数时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31609010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com