I’m trying to verify that a character input to a double variable is of the right data type.
double number = 0;
int validCheck = 0;
char another = 'y';
while(another == 'y')
{
cout<<"Please enter a number: ";
validCheck = scanf("%lf", &number);
while (validCheck !=1)
{
cout<<"Invalid input, please enter a number: ";
validCheck = scanf("%lf", &number);
}
When I compile this, it works fine provided I give a valid input, and an invalid input does put it into the while loop, but rather than checking for another input, it just spams my console with “Invalid input, please enter a number:” without even asking for a new input. What am I missing?
The invalid input remains in the input buffer, so the
scanfis always presented with the same malformed input. You need to clear the input buffer, e.g.