Comparing chars in C
I have a quick question. I have one method called test(). And my code looks like:
void test()
{
char c;
printf("Are you happy?\n");
printf("Hit y for yes or n for no \n");
scanf("%d", &c);
if(c == 'y')
{
printf("That's awesome!\n");
}
else
{
printf("That is too bad.\n");
}
}
When I run the code, the input is not read. I think my problem is in the line "if(c =='y')" Can anyone tell me what I am doing wrong/how to fix it? Thanks!
p.s I have a main method e开发者_JS百科tc.
This scans for an int
:
scanf("%d", &c);
This scans for a char
:
scanf("%c", &c);
The proper scanf
format specifier for reading a single char
value is "%c"
. You are using "%d"
. Format specifier "%d"
is intended to be used exclusively with int
recipient arguments. Why are you trying to use "%d"
with a char
?
You should change it to scanf("%c", &c)
Your problem is the scanf
, it should have %c
for reading a char
See here for more details on scanf
精彩评论