0

I am a new cpp learner and currently trying the std iostream library. I am working on a program that takes number as input and output the number, and exit when enter 0. Also I want the program can ignore the invalid input, output an error message when encounter an invalid input and continue reading the number until I enter 0 to exit. Below is the code I wrote:

while (true) {
        cout << "Please input value" << endl;
        cin >> value;
        if (cin.fail()) {
            cerr << "Invalid input" << endl;
        } else if (value == 0) {
            cout << "Exit with 0";
            break;
        } else {
            cout << "You have entered " << value << endl;
        }
    }

The code does not work as I expected. When I input normal number and it worked well, output each number until I entered 0:

Please input value
1
You have entered 1
Please input value
2
You have entered 2
Please input value
0
Exit with 0

However when I entered something not a number, then the cin won't work in the next while loop and repeatedly output the error message:

Please input value
a
Invalid input
Please input value
Invalid input
Please input value
Invalid input
Please input value
Invalid input
Please input value
more lines

I assume that when a cin fail, it will not read another number in the next loop. I was wondering how can I "reactivate" the cin to make it read number even it failed previously.

Any help is appreciated.

David.S
  • 56
  • 1
  • 2
    You need to add `cin.clear()` to clear the error flag after an error occurs. You'll also need a `cin.ignore(...)` to clear out the invalid input or it will just error again. – Retired Ninja Jan 03 '23 at 23:51

0 Answers0