gpt4 book ai didi

c++检查从文件读取的输入失败

转载 作者:行者123 更新时间:2023-11-28 06:23:58 25 4
gpt4 key购买 nike

我正在编写一个简单的程序来从文件中读取一系列整数并输出它们的总和。我要确保输入确实是一个整数,如果不是,则退出程序。我认为我做的一切都是对的,但程序在收到无效输入时不会中断。我正在使用包含以下内容的文件对此进行测试:1 2 3 4 5 6 7 8 bla 9有什么我在这里没有看到的吗?

谢谢

#include <iostream>
#include <Fstream>

using namespace std;

int main(int argc, char const *argv[])
{
ifstream dataFile;
int number, total = 0;

if (argc < 2) { cout << "You forgot to specify the file name." << endl; exit(-1);}

dataFile.open(argv[1]);

while (dataFile>>number){
if(dataFile.fail()) {cout<< "Found a not number"<<endl; exit(-2);}
else total += number;
}

cout << total << endl;
dataFile.close();
return 0;

最佳答案

如果输入错误,condition while 循环的 fail

while (dataFile>>number){  // will fail 

因此程序将永远不会到达具有这种错误状态的这一行:

if(dataFile.fail())  

你可以试试:

while (datafile >> number){  // loop until problem
total += number;
}
if (dataFile.fail() && !datafile.eof()) { // if problem is bad input
cout << "Found a not number" << endl;
exit(-2); // then stop
}

关于c++检查从文件读取的输入失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28844112/

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