Infinite Loop Issue in C Program Accepting Letters as Integer Input
This issue arises when the program expects an integer input, but the user enters a letter instead. The program enters an infinite loop due to an unexpected character in the input stream. This results in a continuous display of the message "The number you have entered is negative. Please enter a positive number to continue." without providing the user a chance to enter a valid number.
Explanation
The underlying reason for this issue lies within the behavior of the C input stream. When the user enters a non-numeric character, the input stream's "failbit" flag is set. However, the stream is not cleared, so the program remains stuck in the same loop iteration, attempting to read the invalid character repeatedly.
Solution
To resolve this problem, it is necessary to implement proper input validation and error handling. Here is an example of how to address this issue:
#include <iostream> #include <limits> // ... (remaining code) cout << "\nPlease enter a positive number and press Enter: \n"; 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:
The above is the detailed content of Why Does Letter Input Cause an Infinite Loop in My C Program?. For more information, please follow other related articles on the PHP Chinese website!