C 如何比较“中的字符串”;如果;陈述

C 如何比较“中的字符串”;如果;陈述,c,string,C,String,我想测试并查看类型为“char”的变量是否可以与常规字符串(如“cheese”)进行比较,如: #include <stdio.h> int main() { char favoriteDairyProduct[30]; scanf("%s",favoriteDairyProduct); if(favoriteDairyProduct == "cheese") { printf("You like cheese too!");

我想测试并查看类型为“char”的变量是否可以与常规字符串(如“cheese”)进行比较,如:

#include <stdio.h>

int main()
{
    char favoriteDairyProduct[30];

    scanf("%s",favoriteDairyProduct);

    if(favoriteDairyProduct == "cheese")
    {
        printf("You like cheese too!");
    }
    else
    {
        printf("I like cheese more.");
    }

    return 0;
}
#包括
int main()
{
char Favorite乳制品[30];
scanf(“%s”,最受欢迎的乳制品);
if(favoriteDairyProduct==“奶酪”)
{
printf(“你也喜欢奶酪!”);
}
其他的
{
printf(“我更喜欢奶酪。”);
}
返回0;
}
(我实际上想做的事情比这要长得多,但这是我一直坚持的主要部分。)
那么如何比较C中的两个字符串呢?

看看函数和。

您不能使用
==
运算符比较字符数组。您必须使用字符串比较函数。看一看

标准库的
strcmp
函数比较两个字符串,如果它们相同,则返回0;如果第一个字符串按字母顺序“小于”第二个字符串,则返回负数;如果第一个字符串“大于”,则返回正数


您正在从
string.h
中查找函数
strcmp
,或
strncmp

由于字符串只是数组,您需要比较每个字符,因此此函数将为您执行以下操作:

if (strcmp(favoriteDairyProduct, "cheese") == 0)
{
    printf("You like cheese too!");
}
else
{
    printf("I like cheese more.");
}
进一步阅读:


godspeed

顺便说一句,像这样使用scanf()是一个非常严重的错误。如果您输入的单词超过30个字符,您的程序可能会崩溃。fgets()更安全。这里与公认的答案有什么不同?@zar简单的差异,但差异是否定的,而不是==0。
if(!strcmp(favoriteDairyProduct, "cheese"))
{
    printf("You like cheese too!");
}
else
{
    printf("I like cheese more.");
}
if(!strcmp(favoriteDairyProduct, "cheese"))
{
    printf("You like cheese too!");
}
else
{
    printf("I like cheese more.");
}