在C中,当提示用户输入字符串时,会产生不合需要的输出

时间:2013-03-14 07:26:35

标签: c string user-input

有人可以解释为什么即使用户输入“古典”或“爵士乐”,前进的代码块总会导致“抱歉,这不是其中一种选择”?

#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;
}

4 个答案:

答案 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.");

如果ab是两个C字符串,则a == b不会按照您的想法执行。它会检查ab是否指向相同的内存,而不是检查它们是否由相同的字符组成。

在您的情况下,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函数来比较字符串。