PDA

View Full Version : help with simplistic C code


Juntao
Oct23-04, 04:01 AM
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.

photon_mass
Oct23-04, 04:20 AM
check the ascii code of the user input. if it isn't in the range of values assigned to numbers, then print an error message.

maverick280857
Oct23-04, 10:25 AM
The problem is with the scanf argument. You should instead allow the user to enter an alphanumeric input and add a few lines to parse it and check if it is indeed a number (and not a spurious input).

Hurkyl
Oct23-04, 10:38 AM
You should try to avoid using scanf entirely... in this case you're interested in a single digit, so getchar() would be simple to use.