是什么导致 strcmp 返回 0、1 或 -1 以外的值?

问题描述 投票:0回答:2

我有这段代码。当我运行它时,它返回 13、-13 和 0。 如果

str1
大于
str2
,不是应该返回 1,如果
str1
小于
str2
,不是应该返回 -1 吗?

我得到 13、-13 和 0。

#include <iostream>
#include <string>
#include <cstring>

int main() {

    char str1[] = "Megadeth";
    char str2[] = "Metallica";

    // Should return -1 because "Megadeth" < "Metallica" lexicographically
    int result = strcmp(str1, str2);

    std::cout << "Comparing " << str1 << " and " << str2 << ": " << result << std::endl;

    // Should return 1 because "Metallica" > "Megadeth" lexicographically
    result = strcmp(str2, str1);

    std::cout << "Comparing " << str2 << " and " << str1 << ": " << result << std::endl;

    // Should return 0 because "Megadeth" = "Megadeth" lexicographically
    result = strcmp(str1, str1);

    std::cout << "Comparing " << str1 << " and " << str1 << ": " << result << std::endl;

    return 0;
}

结果如下:

Comparing Megadeth and Metallica: -13
Comparing Metallica and Megadeth: 13
Comparing Megadeth and Megadeth: 0

我刚刚遵循了互联网上的教程,他们说它应该返回那些。我不知道是什么原因造成的。

c++ strcmp
2个回答
4
投票

strcmp
未定义为返回 1、0 或 -1。如果第一个按字典顺序大于第二个,则结果为正;如果第一个按字典顺序小于第二个,则结果为负;否则为 0。仅定义符号或 0,而不定义大小。

man strcmp

strcmp()
strncmp()
函数根据字符串s1大于、等于或小于字符串s2返回大于、等于或小于0的整数。比较是使用无符号字符完成的,因此 '�' 大于 ` '。

首先出现的字母,至少在您的实现中,被认为是“较小的”。因此,

Megadeth
Metallica
之间不匹配的第一个字母是
g
t
t
大于
g
,因此当
Metallica
是第二个时,结果为负数。


3
投票

参见:

https://en.cppreference.com/w/c/string/byte/strcmp

返回值不限于-1..1.

© www.soinside.com 2019 - 2024. All rights reserved.