Dealing with format errors in a file

I'm actually trying to learn C++ and I have to write a program that reads a sequence of whitespace-separated integers from a file and then calculates the sum. The exercise itslef isn't hard and I came up with this function to read data from a file :

1
2
3
4
5
6
7
8
9
// read whitespace-separated integers from a file 
void fill_from_file(vector<int>& integers, const string& name)
{
    ifstream ist{ name }; 
    if (!ist) error("Can't open input file : ", name); 

    for (int i; ist >> i;) integers.push_back(i); 

} 




So basically I just keep reading integers from a file until end of file. I have learnt the basics of dealing with files by using the Stroustrup's book programming principles and practice using C++, but I have some doubts about error handling when dealing with files.

The author in his examples along the chapter just shows dealing with error in files with throwing an exception, instead of writing input loops where he tries to recover from a failed read like when we get input from the keyboard.

Q1) What is the best approach when dealing with format errors when reading data from a file ? For example, suppose that instead of an integer my function finds an 'x', should I try to recover from this error ? Or should I just give up and abandon the attempt to read more data from that file?

Q2) Another example : In this same program but with input from cin the author shows the use of a skip_to_int() function that, after a failed read, skips characters until it finds an integer. Would this kind of approach be worth for a file too ? Is this approach worth for a simple program like this ?
Last edited on
It depends on the source of the file, and what it is expected to contain.
Unless there's a good reason to continue, to issue an information message and exit the program (or current action) might be reasonable.
Topic archived. No new replies allowed.