2

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.

moriaz
  • 41
  • 6

0 Answers0