Home >Backend Development >C++ >How to Prevent Infinite Loops When Inputting Non-Numeric Values in C ?
Infinite Loop when Entering a Letter Instead of a Number
When encountering a character input rather than an integer, the provided code falls into an infinite loop while displaying the message "The number you entered is negative. Please enter a positive number to continue." This occurs due to the following:
Issue:
The cin stream is not properly handled when it encounters invalid input (a character in this case). It leaves the stream in an erroneous state, known as the "failbit" flag being set.
Solution:
To resolve this issue, implement the following steps:
Check for successful input when reading the number (using cin with the stream manipulation operator >>):
while (!(cin >> num1)) { cout << "Incorrect input. Please try again.\n"; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); }
Clear the stream and ignore the erroneous input characters if cin fails (using clear() and ignore()):
By implementing these steps, the program will detect the invalid input, clear the stream, and prompt the user to enter a positive integer, allowing the program to continue without an infinite loop.
The above is the detailed content of How to Prevent Infinite Loops When Inputting Non-Numeric Values in C ?. For more information, please follow other related articles on the PHP Chinese website!