- #1
Juntao
- 45
- 0
Hi, I am trying to write a loop that will check a users input to be between a certain numeric range in C. The thing is, I expect the person to enter a number, not a character.
When the person enters a character, the loop becomes infinite. Thats the problem.
If you look at example source code below:
#include <stdlib.h>
int main()
{
int number=0;
printf("input a number\n");
scanf("%d", &number);
while (number <1 || number >5)
{
printf("incorrect number!\nput in new number");
scanf("%d", &number);
printf("\n your number is %d",number);
}
printf("\n your number is: %d",number);
return 0;
}
it works fine for numbers, but if I enter letter 'a' for example, the loop becomes infinite.
My question is, how do I go about the code such that a character that is inputted instead of a number prints error to screen and prompts user over again?
I thought a statement like this while (number <1 || number >5) would do the trick, but it does not.
When the person enters a character, the loop becomes infinite. Thats the problem.
If you look at example source code below:
#include <stdlib.h>
int main()
{
int number=0;
printf("input a number\n");
scanf("%d", &number);
while (number <1 || number >5)
{
printf("incorrect number!\nput in new number");
scanf("%d", &number);
printf("\n your number is %d",number);
}
printf("\n your number is: %d",number);
return 0;
}
it works fine for numbers, but if I enter letter 'a' for example, the loop becomes infinite.
My question is, how do I go about the code such that a character that is inputted instead of a number prints error to screen and prompts user over again?
I thought a statement like this while (number <1 || number >5) would do the trick, but it does not.