-2

我有这个下面的程序

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char text1[30],text2[30];
    int diff;
    puts("Enter text1:");
    fgets(text1,30,stdin);
    puts("Enter text2:");
    fgets(text2,30,stdin);
    diff=strcmp(text1,text2);
    printf("Difference between %s and %s is %d",text1,text2,diff);
}

如果我将 text1 作为 inputtext 并将 text2 作为 differencetext ,那么差异应该是 5 ,但是对于不同的输入我得到 1 ,我不确定我哪里出错了。

4

5 回答 5

6

The specification for strcmp in the C standard says only that it “returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2” (C 2011 N1570 7.24.4.2 3, C 2018 ibid).

You may not rely on more specific behavior, such as returning a specific value, unless you have an additional guarantee from your C implementation.

于 2013-08-15T13:49:28.867 回答
5

All that the specifications say is that strcmp will return a number "less than", "greater than" or "equal to" zero depending on the result of the comparison.

I'm not sure why you believe that the difference should be 5.

于 2013-08-15T13:49:32.017 回答
3

I think you misunderstood what strcmp does:

int strcmp(const char *s1, const char *s2);

Upon completion, strcmp() shall return an integer greater than, equal to, or less than 0, if the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2, respectively.

于 2013-08-15T13:49:19.927 回答
0

来自cplusplus.com

关于strcmp返回值

返回一个整数值,表示字符串之间的关系:零值表示两个字符串相等。大于零的值表示第一个不匹配的字符在 str1 中的值大于在 str2 中的值;小于零的值表示相反。

于 2013-08-15T13:49:35.090 回答
-1

That's because strcmp return an int: negative if first is less than second, positive non-zero if second is less that first and 0 if equal.

于 2013-08-15T13:49:22.853 回答