有人可以解释为什么即使用户输入“古典”或“爵士乐”,前进的代码块总会导致“抱歉,这不是其中一种选择”?
#include <stdio.h>
int main()
{
char c[20];
printf("Hey! I hear you like music! What type do you like? (Classical/Jazz/Rock) ");
gets(c);
if(c == "Classical" || c == "classical")
printf("Classical music is great.");
else if(c == "Jazz" || c == "jazz")
printf("Jazz is awesome!");
else
printf("Sorry, that's not one of the choices.");
getchar();
return 0;
}
答案 0 :(得分:3)
在C中,您必须使用strcmp()
来比较字符串:
if(strmp(c, "Classical") == 0 || strcmp(c, "classical") == 0)
printf("Classical music is great.");
else if(strcmp(c, "Jazz") == 0 || strcmp(c, "jazz") == 0)
printf("Jazz is awesome!");
else
printf("Sorry, that's not one of the choices.");
如果a
和b
是两个C字符串,则a == b
不会按照您的想法执行。它会检查a
和b
是否指向相同的内存,而不是检查它们是否由相同的字符组成。
在您的情况下,c == "Classical"
等总是评估为false。
答案 1 :(得分:2)
if(c == "Classical" || c == "classical")
以上是无效的字符串比较。请改为使用strcmp
,如下所示:
if(0 == strcmp(c, "Classical")) { // if c and "Classical" are equal
printf("equal!\n");
}
点击here作为参考页。
答案 2 :(得分:0)
您必须将它们作为字符串进行比较。
if(strcmp(c,"Classical")==0 || strcmp(c,"classical")==0)
printf("Classical music is great.");
else if(strcmp(c,"Jazz")==0 || strcmp(c,"jazz")==0)
printf("Jazz is awesome!");
else
printf("Sorry, that's not one of the choices.");
答案 3 :(得分:0)
在C语言中,你不能直接比较字符串指针,因为它实际上只是比较实际的指针而不是它们所指向的指针。
由于字符串文字总是指针,并且数组可以衰减为指针,你正在做的是比较指针。
实际上,在比较它们的指针时,你甚至无法确定两个相同的字符串文字是否相等。编译器可以将字符串存储在不同的位置,即使它们是相同的。
正如其他人所解释的那样,在C中你必须使用strcmp
函数来比较字符串。