I was trying out a simple program in C for validating user data. The program is supposed to identify whether a user entered character is a number, alphabet or a special character.
Somehow , the code identifies every kind of input character as a number. I have appended the code below, I'd be grateful if someone could kindly point out where I'm going wrong ?
//Program to take input from the user and determine whether it is character, number, or a special character
#include<stdio.h>
#include<conio.h>
#include<string.h>
char ch;
int main()
{
clrscr();
printf("Enter a character \n");
scanf("%c \n",ch);
if ((ch>='A'&& ch<='Z')||(ch>='a'&& ch<='z') )
{
printf("The character entered is an alphabet \n" );
}
else if ((ch>=0)&&(ch<=9))
{
printf("Character entered is an number \n");
}
else
{
printf("Character entered is a special character");
}
return 0;
}
scanf accepts a pointer as the argument for %c. In other words,
scanf("%c \n",ch);
should be written as:
scanf("%c\n",&ch);
Without the reference operator (&), scanf receives the value of ch. In this case, the value is garbage, because ch is unset.* Referencing ch gives scanf a pointer to ch, not ch itself, so scanf can modify the value of ch by dereferencing the pointer (using the dereference operator, *).
There's also the issue with digit checking that Himadri mentioned.
* This is actually undefined behaviour.
Oh, Arun very silly mistake. In your second condition in else if you have to right 0 and 9 in single quotation mark.
So, your code will be -
if ((ch>='A'&& ch<='Z')||(ch>='a'&& ch<='z') )
{
printf("The character entered is an alphabet \n" );
}
else if ((ch>='0')&&(ch<='9'))
{
printf("Character entered is an number \n");
}
else
{
printf("Character entered is a special character");
}
May be this is the only mistake. Now, it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With