I am writing a simple program to read a series of integers from file and output their sum. I am to make sure that the input is indeed an integer, and exit the program if it isn't. I think I am doing everything right, but the program won't break when it is given invalid input. I am testing this with a file containing: 1 2 3 4 5 6 7 8 bla 9 Is there something I am not seeing here?
Thanks
#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;
}
Aucun commentaire:
Enregistrer un commentaire