How to prevent non-numeric input in C & ask user input again

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?



from Recent Questions - Stack Overflow https://ift.tt/2Vczarm
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations