I am new to the forum. I am trying to validate user input to be between 1 to 100. Anything lower or higher will ask user to key in number again. It works fine with numbers, however, if user input alphabet, it keeps looping endlessly. Below is my code, kindly help to take a look and suggest where it went wrong and how i can fix it. Thanks a lot indeed.
#include <stdio.h>
int main()
{
float number;
do
{
printf("Please key in number (between 1 to 100) : ");
number = 0;
scanf("%f", &number);
printf("Amount you key is:%0.2f\n", number);
}while(!(number>= 1 && number<= 100));
printf("Valid number\n");
return 0;
}
If you use a C++ compiler, write C++ code! It's sure easier than C:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std; //if you want
int main()
{
cout << "Enter a value in the range (0, 100]: ";
int v;
while((cin >> v), (v > 100 || v <= 0))
{
cin.clear();
cout << "Try again: ";
}
cout << "You entered a valid value of " << v << endl;
cin.sync(); cin.ignore(cin::size_type(-1), '\n'); //hold console open
}