简体   繁体   English

IF - 条件与char比较不在C中工作

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM