Hi. I'm having a problem with this code. If I enter an integer value, it works just fine. However, if I type in a non-integer value, it keeps printing out the error message rather than going back to the user input. It's stuck in an infinite loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int error;
int goalCalorie;
do
{
error = 0;
cin >> goalCalorie;
cin.ignore(100,'\n');
if (goalCalorie > 0 && goalCalorie < 10000)
{
cout << "Your calorie goal has been set to: " << goalCalorie << endl;
}
else
{
cout << "Please enter a valid number: ";
++error;
}
} while (error > 0);
I had a go at this, and didn't get the same results as you. Perhaps your system does IO in an unexpected way?
Here's are 2 sample sessions, I've re-posted the code afterwards, just so you can be sure it's the same code.
$ ./a.out2Your calorie goal has been set to: 2
$ ./a.out-2Please enter a valid number: -4Please enter a valid number: 4Your calorie goal has been set to: 4
$
The loop will be infinite if you enter a bad value at the start, because error will always be greater than 0... so if you enter a bad value error is incremented and will "always" be greater than 0.
I would suggest using a flag controlled while loop
where the flag is set to true and changed to false if the user enters a good value.
I get those same results. My problem is if the user somehow enters in for example... "Two" instead of "2". I would like to prevent the end user from entering a non-digit value. With my current code, if you enter a non-digit value, it goes into an infinite loop.
Ummm idk... i guess since the program trys to store a string inside an interger type it malfunctions, maybe if you add an if statement to check if the value entered is not of type int then do somthing
You guys are both right.
I put the cin in the condition and tested it to a true/false value. (Per coltehrman.)
It still went into an infinite loop, but cin has to be emptied or it gets bypassed. (Per PCrumley48.)
After that, it worked perfectly.
Thank you guys for the help!!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main()
{
int goalCalorie;
while (!(cin >> goalCalorie))
{
cout << "Please enter a valid number: ";
cin.clear();
cin.ignore(100,'\n');
}
cout << "Your calorie goal has been set to: " << goalCalorie << endl;
}