I use the following to get two integers from user input, and also to check they are actually numbers...now it works fine if I enter an incorect number (say the first number) and asks me to re-enter, however if I enter an invalid number again then it goes into an eternal loop. But I cant spot the problem?
Any help or a solution would be much appreciated.
Code:
void userInput(char value[])
{
int number1, number2;
cout << "Please enter a number you wish to " << value << ":" << endl;
cin >> number1;
while (!cin >> number1)
{
cout << "Error! You have entered an invalid number, " << flush;
// clear the state of cin, otherwise the while condition loops indefinently.
cin.clear();
cin.ignore(INT_MAX, '\n');
cout << "Please re-enter a number:" << endl;
cin >> number1;
}
cout << "Please enter a number you wish to " << value << " " << number1 << " by" << endl;
cin >> number2;
while (!cin >> number2)
{
cout << "Error! You have entered an invalid number, " << flush;
cin.clear();
cin.ignore(INT_MAX, '\n');
cout << "Please re-enter a number:" << endl;
cin >> number2;
}