Reputation: 43
I really don't know what's the mistake. It seems to be right, doesn't it?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char op;
printf("Type in operator (+,-,/,*):");
scanf("%i",&op);
if(op == '+')
{
printf("You entered a plus");
}
system("pause");
return 0;
}
I expected it to print "You entered a plus" when entering a +. It does not.
I'm kinda new to C. Thanks in advance :)
Upvotes: 4
Views: 949
Reputation: 43
Your problem is with wrong format specifier
//In scanf instead of
scanf("%i",&op);
// you have to provide
scanf("%c",&op);
%i use for reading integer whereas %c use for reading char.
Upvotes: 0
Reputation: 23727
scanf("%i", &op);
You are expecting an integer. So, when you write a character and press <Enter>
, scanf
fails (you can check its return value to see it):
if (scanf("%i", &op) != 1)
{
/* Treat the error. */
}
Use rather %c
format in scanf
to read characters:
scanf("%c", &op);
Upvotes: 0
Reputation: 500963
The if
condition is fine. The problem is the scanf()
format, which should be
scanf("%c",&op);
(%i
reads an integer whereas %c
reads a char
.)
Upvotes: 4