Reputation: 329
i have looked through other scanf posts but i cant seem to find the issue i have here with this short code. The thing is when i enter a b or c, it doesnt go to the if or else if statements, i cant really figure out how to fix it, any help would be lovely! thank you!
#include <stdio.h>
int main(void)
{
char bogstav, a, b, c;
printf("Indtast a b eller c\n");
scanf("%c", &bogstav);
if(bogstav == a)
{
printf("Du valgte a");
}
else if(bogstav == b)
{
printf("Du valgte b");
}
else if(bogstav == c)
{
printf("Du valgte c");
}
else
{
printf("Du valgte ikke a b eller c!");
}
return 0;
}
Upvotes: 0
Views: 415
Reputation: 863
two ways you can do it by declaring varriable
char a='a',b='b',c='c';
or
without declaring varriable check directly in condition like below
if(bogstav == 'a')
{ // do your stuff }
Upvotes: 0
Reputation: 593
The problem in your code is that you want to compare bogstav to the value of the c character, not of the c value, but you're doing it in the other way :P
Just do if ( bogstav == 'b' ) to check if bogstav is equal to the b characcter.
#include <stdio.h>
int main(void)
{
char bogstav;
printf("Indtast a b eller c\n");
scanf("%c", &bogstav);
if(bogstav == 'a')
{
printf("Du valgte a");
}
else if(bogstav == 'b')
{
printf("Du valgte b");
}
else if(bogstav == 'c')
{
printf("Du valgte c");
}
else
{
printf("Du valgte ikke a b eller c!");
}
return 0;
}
Upvotes: 0
Reputation: 35520
a
, b
and c
in the if
statements are not characters, they are variables, which have not been initialized. You want to compare to 'a'
, etc. Or do char a = 'a';
... , but that's probably overkill.
Upvotes: 0
Reputation: 324
Are you expecting those to be literal characters?
if(bogstav == 'a')
Upvotes: 0