-
spot the error
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;
}
-
PHP Code:
while (!cin >> number1) {
}
Shouldn't it be
PHP Code:
while (!number1) {
}
since you already got the value of number1 from the cin >> number1; above that.
Correct me if I'm wrong.
-
Your way seems to produce the same error too so there must be something wrong possibly elsewhere Ill keep looking in the code
-
If anyone is interested in the whole code (not that long).
a colour coded, spaced link is available here
-
cool ... do you own your own domain? How much did you pay for it?
-
Code:
int num1, num2;
int flag = 0;
while(flag == 0)
{
cout << "enter an integer value for num1" << endl;
cin >> num1;
if(cin.fail())
{
cout << "data entry error. try again" << endl;
cin.clear();
}
else
flag == 100;
}
flag = 0;
//now repeat code for num2;