Infinite Loop with Invalid Input and cin
When using cin to read input, an infinite loop can occur if the input is not of the expected type. This issue is particularly apparent when attempting to input numbers but accidentally entering characters.
The problem stems from the fail state that cin enters when it encounters invalid input. In such scenarios, cin will不再 prompt for input, resulting in an infinite loop.
To prevent this behavior, one solution is to check if cin is in the fail state. If it is, the fail state is cleared, and the bad input is discarded using cin.ignore(). This allows cin to return to its normal operation and prompt for further input.
if (cin.fail()) { cout << "ERROR -- Invalid input detected" << endl; cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); }
Alternatively, you can use std::getline() to read the input as a string and perform more sophisticated validation checks before trying to convert it to a number. This approach provides greater flexibility and allows for more complex input validation.
The above is the detailed content of How to Prevent Infinite Loops Caused by Invalid Input with `cin`?. For more information, please follow other related articles on the PHP Chinese website!