[英]IF - condition with char comparison not working in C
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 :) 我是C的新手。先谢谢你:)
The if
condition is fine. if
条件没问题。 The problem is the scanf()
format, which should be 问题是
scanf()
格式,应该是
scanf("%c",&op);
( %i
reads an integer whereas %c
reads a char
.) (
%i
读取整数,而%c
读取char
。)
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): 因此,当您编写一个字符并按
<Enter>
, scanf
失败(您可以检查其返回值以查看它):
if (scanf("%i", &op) != 1)
{
/* Treat the error. */
}
Use rather %c
format in scanf
to read characters: 在
scanf
使用%c
格式来读取字符:
scanf("%c", &op);
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.