I am new to C++ coding.
I have noticed that if I enter multiple characters for a character variable then the test program given below goes into an infinite loop. I am not able to debug this issue properly. Can someone help me see how the flow of the program goes when such input is entered. I doubt about some unsafe conversions happening.
There is a possibility that the overflow values are taken as input for next integer variable, but I am checking for variable in a loop and asking the user to
re-enter a value is invalid. The program does not halt for taking new input for number. Instead it infinitely prints “Enter a Number”. Why is it that the cin is not working for
taking the new input? Is there some modification in this program that can rectify this error?
#include <iostream>
int main()
{
char name;
int number=-1;
cout << "Enter a character: \n";
cin >> name; //Use input like abc here
cout << "number = " << number;
while (number == -1)
{
cout << "Enter a number: \n";
cin >> number; // This never waits for user input
}
return 0;
}
Output
Enter a character:
ytc
number = -1Enter a number:
Enter a number:
Enter a number:
When the user enters mutiple characters on the first query, only the first one is extracted and stored in
name.After that, the loop is entered. The first character is read, and it is not a number, thus the stream goes into a bad state. All subsequent reads fail, so the value of
numbernever changes, and you have an infinite loop.The following program will do what you want:
The condition
if(!(std::cin >> number))checks if the extraction was successful. If not, an error-message is printed, the stream-state is cleared, and one character extracted. The latter is done to prevent an infinite loop, because if we never extract the bad character, we will get the same error over and over again.Note that the extraction
std::cin >> numberwill try to extract the longest string that represents a number. If the user inputs234t23432, then it will extract234, because thetis the first character that can not be interpreted as part of the number.