Reputation: 5
I was wondering if you guys could explain to me why this loop doesn't loop if I enter 'r' in for the value of 'value'.
double value
std::cout << "Please enter a real number: ";
std::cin >> value;
while (!isdigit(value))
{
std::cout << "Sorry, but only numbers are valid.\nPlease enter a real number: ";
std::cin >> value;
}
Thank you very much.
Upvotes: 0
Views: 232
Reputation: 33106
You did two things wrong: You declared value
as a double
, and you used std::cin >> value
to populate that incorrectly declared variable.
You need to read a character, so read a character. Declare value
as a char
.
Edit: I am assuming your assignment is to read a character and see if it represents one of the numeric digits. If your assignment is to read a number, you are going about this all wrong.
Upvotes: 1
Reputation: 3122
You shouldn't be using isdigit()
here because that's for testing whether a single char
type is an ASCII digit.
If you're expecting the user to enter a real number (and not a string), then you should use cin.fail()
as your loop test condition. If cin
reads a string when it's expecting a double
then cin.fail()
will return true
.
Another (cleaner) option is to just test the state of cin
as @bennofs pointed out:
while (!(std::cin >> value))
{
// bad value was entered
}
Upvotes: 2