I use cin.fail() to check if the last input failed: int x; cin >> x; if (cin.fail()) { /* handle error */ } detects when the user typed invalid data. It returns true if extraction failed.
After detecting failure, clear the error state and remove bad input: cin.clear(); resets the flags, and cin.ignore(1000, '\n'); discards the invalid data. You need both steps. A complete validation loop: while (cin.fail()) { cin.clear(); cin.ignore(1000, '\n'); cout << "Invalid: "; cin >> x; } keeps asking until the user provides valid input.