Home >Backend Development >C++ >How to Prevent Infinite Loops When Taking Integer Input in C ?
Infinite Loop Issue with Character Input
When executing the provided code, an infinite loop occurs if a non-integer character is entered instead of a number. This behavior arises during the verification process for a positive number.
Specifically, the issue lies within the inner while loop that checks the validity of num1. If a letter character is entered, the cin >> num1 statement fails, setting the failbit flag. However, the cin buffer is not cleared, leading to the incorrect assumption that the same invalid input persists.
Fixing the Issue
To address this issue, additional logic is required to handle invalid input and clear the cin buffer:
do { while(!(cin >> num1)) { cout << "Incorrect input. Please try again.\n"; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); } if(num1 < 0) cout << "The number you entered is negative. Please enter a positive number to continue.\n"; } while(num1 < 0);
In this modified code, an outer do-while loop is employed to continuously prompt for input until a valid positive integer is entered.
After an invalid character is entered, cin.clear() is called to reset the failbit flag. Subsequently, cin.ignore() is used to discard all remaining characters from the input buffer, including the invalid character and any whitespace or newline characters that may follow. The numeric_limits With these adjustments, the code ensures that only valid integer inputs are processed and infinite loops are avoided when non-integer characters are entered. The above is the detailed content of How to Prevent Infinite Loops When Taking Integer Input in C ?. For more information, please follow other related articles on the PHP Chinese website!