How to compare a char?

北城以北 提交于 2020-11-26 06:41:08

问题


I am learning c. I have a question. Why doesn't my program work?

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

char cmd;

void exec()
{
        if (cmd == "e")
        {
                printf("%c", cmd);
                // exit(0);
        }
        else
        {
                printf("Illegal Arg");
        }
}

void input()
{
        scanf("%c", &cmd);
        exec();
}

int main()
{
        input();
        return 0;
}

I insert a "e" but it says illegal arg.
cmd is not equal to "e". Why? I set cmd with scanf to "e".


回答1:


First of, in C single quotes are char literals, and double quotes are string literals. Thus, 'C' and "C" are not the same thing.

To do string comparisons, use strcmp.

const char* str = "abc";
if (strcmp ("abc", str) == 0) {
   printf("strings match\n");
}

To do char comparisons, use the equality operator.

char c = 'a';
if ('a' == c) {
   printf("characters match\n");
}



回答2:


cmd is a char type but "e" is a string not a char type,you should write like this if(cmd == 'e')



来源:https://stackoverflow.com/questions/17766754/how-to-compare-a-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!