在C语言中比较两个字符串?

32

这段代码无法正常工作,因为没有进行比较。为什么呢?

所有的名字都通过了if判断。

printf("Enter Product: \n");
scanf("%s", &nameIt2);
printf("Enter Description: \n");
scanf("%s", &descriptionI);
printf("Enter Quantity: \n");
scanf("%d", &qtyI);
printf("Enter Order Quantity: \n");
scanf("%s", &ordqtyI);

while (fscanf(fp4, "%s %s %d %s\n", &namet2, &description2, &qty2, &ordqty2) != EOF){
    if(namet2 != nameIt2)
        fprintf(fpt2, "%s %s %d %s\n", &namet2, &description2, qty2, &ordqty2);
}

2
scanf("%s", &variable) 看起来有问题。数组名称“衰变”为指向第一个元素的指针,因此根据变量类型,& 要么是不必要的,要么是严重的错误。 - Lundin
8个回答

72

要比较两个C字符串(char *),请使用strcmp()。当字符串相等时,该函数返回0,因此您需要在代码中使用它:

if (strcmp(namet2, nameIt2) != 0)

如果您(错误地)使用

if (namet2 != nameIt2)

你正在比较两个字符串的指针(地址),在你的情况下这些指针总是不同的,因此比较结果为不相等。


15

要比较两个字符串,可以使用内置函数strcmp(),需要包含头文件string.h

if(strcmp(a,b)==0)
    printf("Entered strings are equal");
else
    printf("Entered strings are not equal");

或者您可以编写自己的函数,就像这样:

int string_compare(char str1[], char str2[])
{
    int ctr=0;

    while(str1[ctr]==str2[ctr])
    {
        if(str1[ctr]=='\0'||str2[ctr]=='\0')
            break;
        ctr++;
    }
    if(str1[ctr]=='\0' && str2[ctr]=='\0')
        return 0;
    else
        return -1;
}

7

您当前正在比较两个字符串的地址。

使用strcmp比较两个char数组的值。

 if (strcmp(namet2, nameIt2) != 0)

3

在此处比较的是指针,而不是指向的内容(即字符)。

您必须使用 memcmpstr{,n}cmp 来比较内容。


2
您需要使用 strcmp 函数:
strcmp(namet2, nameIt2)

2

数组的名称表示其起始地址。 namet2nameIt2 的起始地址不同。因此等于 (==) 运算符检查地址是否相同。要比较两个字符串,更好的方法是使用 strcmp(),或者我们可以使用循环逐个比较字符。


1
回答你问题中的“为什么”:
因为等号操作符只能应用于简单的变量类型,比如float、int或char,而不能应用于更复杂的类型,比如结构体或数组。 要确定两个字符串是否相等,必须明确地逐个字符比较这两个字符串。

0
if(strcmp(sr1,str2)) // this returns 0 if strings r equal 
    flag=0;
else flag=1; // then last check the variable flag value and print the message 

                         OR

char str1[20],str2[20];
printf("enter first str > ");
gets(str1);
printf("enter second str > ");
gets(str2);

for(int i=0;str1[i]!='\0';i++)
{
    if(str[i]==str2[i])
         flag=0;
    else {flag=1; break;}
}

 //check the value of flag if it is 0 then strings r equal simple :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接