C语言 如何比较字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17766754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare a char?
提问by lolxdfly
I am learning c. I have a question. Why doesn't my program work?
我正在学习 C. 我有个问题。为什么我的程序不起作用?
#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".
我插入了一个“e”,但它表示非法参数。
cmd 不等于“e”。为什么?我将带有 scanf 的 cmd 设置为“e”。
回答by Casper Beyer
First of, in C single quotes are char literals, and double quotes are string literals. Thus, 'C' and "C" are not the same thing.
首先,在 C 中,单引号是字符文字,双引号是字符串文字。因此,“C”和“C”不是一回事。
To do string comparisons, use strcmp.
要进行字符串比较,请使用 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");
}
回答by CharlesX
cmdis a char type but "e"is a string not a char type,you should write like this if(cmd == 'e')
cmd是char类型但"e"不是char类型的字符串,你应该这样写if(cmd == 'e')

