Search code examples
c++while-loopifstream

With ifstream while loop, how to show an input error and resume at the next line?


If my input file started with a letter it will stop the while loop because it cant rewrite int1, I know that but how would I be able to detect this and show an error message saying that workinfile>>int1 did not work and afterwards continue the loop?

cin>>filename;
ifstream workingfile(filename);

while (workingfile>>int1>>int2>>string1>>string2) {
    cout<<int1<<int2<<string1<<string2<<endl;
    linenumread++;
}

I tried doing but it doesn't work, any help would be appreciated

 while (workingfile>>int1>>int2>>string1>>string2) {
    if(!(workingfile>>int1))
    {
       cout<<"Error first value is not an integer"<<endl;
       continue;
    }
    cout<<int1<<int2<<string1<<string2<<endl;
    linenumread++;
}

Also would it be possible to detect if it stops reading the strings as well?

The input file would look like this

10 10 ab bc
11 11 cd ef
a  
12 12 gh hi

I want to to detect when it hits an invalid input, show an error message, and continue with the next line in the file.


Solution

  • For this kind of input, it's usually better to read a complete line, and then extract the values from that line. If the line can't be parsed, you can report a failure for that line, and just continue from the start of the next line.

    That would look something like this:

    std::string line;
    while (std::getline(workingfile, line)) // Read a whole line per cycle
    {
        std::istringstream workingline(line); // Create a stream from the line
        // Parse all variables separately from the line's stream
        if(!(workingline>>int1))
        {
           cout<<"Error first value is not an integer"<<endl;
           continue;
        }
        if(!(workingline>>int2)
        {
           cout<<"Error second value is not an integer"<<endl;
           continue;
        }
        // ^^^^ a.s.o. ...
        cout<<int1<<int2<<string1<<string2<<endl;
        linenumread++;
    }