Actually, I can easily found a similar question in Google, but it still can not solve my question.
How to prevent non-numeric input in C?
The upper-link is like a similar case.
Here is my code
#include <stdio.h>
int main()
{
int n;
printf("Enter 1 or 2?\n");
scanf("%d", &n);
while(n != 1 && n != 2)
{
printf("Please do not enter other characters\n");
printf("Enter 1 or 2?\n");
scanf("%d", &n);
}
}
I hope if users enter other numbers(e.g. 1, 45, 656), characters (e.g. a, f, u, e), or string(e.g. apple), the upper program can print out an error message and ask for user input again.
Yes! if users enter other numbers, the program can do what I want. But! if users enter other characters, string, the program will keep looping.
What should I need to add to this program?
fgetsto read the input. Then usesscanfto parse the string read withfgets. Check the return value ofsscanf. It will be1if the input is a valid integer and0otherwise.fgets. Usingfgetsis the best way and if you think there's some problem that prevents you from doing that then please provide the exact details. I will bet that the reason is not actually valid.fgets()and usingstrtol()to extract the value and allow you to check the next character that could not be converted. If the input was not good, it is really easy to loop and input another string.