strcpy能否影响strcmp结果的c语言?

Jav*_*eek 2 c

编辑:更改标题以反映帖子中的两种方法.

我正在尝试比较c语言中的两个字符串,但由于某种原因,它始终打印两个字符串不相等

#include <stdio.h>
#include <string.h>


int main()
{
    /* A nice long string */

    char test[30]="hellow world";

    char test2[30];

    // to copy string from first array to second array

    strcpy(test2, test);



    /* now comparing two stering*/

    if(strcmp(test2, test))
       printf("strigs are equal  ");
    else

    printf("not equal  \n");

    printf("value of first string  is %s and second string is %s",test,test2);
    printf("length of string1 is %zu and other string is %zu ",strlen(test2),strlen(test2));



}
Run Code Online (Sandbox Code Playgroud)

我总是得到输出

not equal  
value of first string  is hellow world and second string is hellow worldlength of string1 is 12 and other string is 12 
Run Code Online (Sandbox Code Playgroud)

Jer*_*fin 11

你的问题在于你的使用方式strcmp.strcmp当字符串相等时返回0(其计算结果为false)(当字符串为"按顺序"时返回正数,当它们"乱序"时返回负数).

  • AFAIK,你不能依靠±1,只能依靠正/负. (3认同)

Ole*_*ksi 6

当两个字符串相同时,strcmp返回0,而在C中,0的计算结果为false.尝试:

if(strcmp(test2, test)==0)
Run Code Online (Sandbox Code Playgroud)