3

I am trying to write a piece of code that continuously reads from the input (cin). It is supposed to ignore the possible errors and continue with reading the next inputs.

At the moment, I know about two possible errors that might occur: EOF (Ctrl + D), or entering a character instead of a number.

Here is a simplified extract of the code, but it does not work when I press Ctrl + D when input is expected.

int ival;
int i = 0;
while(true)
{
    cout << i++ << ": ";
    cin >> ival;
    
    if (!cin.good()) 
    {
        cin.clear(); 
        if (cin.eof()) clearerr(stdin);
        cin.ignore(10000,'\n');
    }
    else
        cout << ival << endl;
}

I have already checked the following posts and some other similar ones. However, each of them handles only one of these errors at a time.

clear and ignore, clearerr.

I have also tried various permutations of the statements in the error handling part, but still not successful.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
moriaz
  • 96
  • 6

1 Answers1

0

Here is a piece of code that handles both EOF(Ctrl+D) and incorrect inputs. It continues reading inputs and ignores invalid ones.

int ival;
for (int i = 0; i < 5; ++i) {
    cin >> ival;
    /*
    if (cin.fail()) cout << "fail" << endl;
    if (cin.eof()) cout << "eof" << endl;
    if (cin.bad()) cout << "bad" << endl;
    if (cin.good()) cout << "good" << endl;
    */

    if (!cin.good()) {
        if (cin.eof()) { //EOF = Ctrl + D
            clearerr(stdin);
            cin.clear(); //this must be done after clearerr
        }
        else { //This handels the case when a character is entered instead of a number
            cin.clear(); //
            cin.ignore(10000,'\n');
        }
    }
    else
        cout << ival << endl;
}
moriaz
  • 96
  • 6