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?
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;
}
}
If you give input as combination of integer and character, then the program doesn't work as expected. Example: If I give input as 1a, the result says the number is odd.
@Vamsi It depends on what you expect. The program above tries to read the first integer from the input and ignores everything after it. This might or might not be what you need. Personally, I wouldn't use
scanf
at all but read an entire line of input viagetline
and see if it is exactly one integer. Well, no, I'd just use the command line arguments for this which would be the better design anyway.