strcmp 不返回 1 和 -1

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

我有这段代码。当我运行它时,它返回 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
1个回答
0
投票

参见:

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

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

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