Warm tip: This article is reproduced from serverfault.com, please click
c

How to prevent non-numeric input in C?

发布于 2015-02-19 18:12:04

I wrote a small C program which will get an input from the user and check if the input is even or odd.

#include<stdio.h>

int main()
{
    int n;
    printf("Enter an integer number: ");
    scanf("%d",&n);

    if(n%2 == 0)
    {
        printf("\n%d is an EVEN number.\n",n);
    }
    else
        printf("\n%d is an ODD number.\n",n);

     return 0;
}

but when I enter an alphabet or a symbol, it shows the output as 0 and says input is EVEN. How can I prevent user from entering alphabets and symbols? What's the easiest way to do that?

Questioner
ruby_r
Viewed
0
5gon12eder 2015-02-20 02:24:34

You have to check the return value of scanf. From the documentation:

Return Value

Number of receiving arguments successfully assigned, or EOF if read failure occurs before the first receiving argument was assigned.

Applied to your code:

#include <stdio.h>
#include <stdlib.h>

int
main()
{
  int n;
  printf("Enter an integer number: ");
  if (scanf("%d", &n) != 1)
    {
      printf("This is not a number.\n");
      return EXIT_FAILURE;
    }
  else if (n % 2 == 0)
    {
      printf("\n%d is an EVEN number.\n", n);
      return EXIT_SUCCESS;
    }
  else
    {
      printf("\n%d is an ODD number.\n", n);
      return EXIT_SUCCESS;
    }
}