0

我知道下面的代码正在输出布尔问题的结果,但我不明白为什么它输出 1 和 0 而不是 1 和 1。

#include <iostream>
using namespace std;

int main() 
{
    string d = "abc", e = "abc";
    char a[] = "abc", b[] = "abc";
    cout << (d == e);
    cout << (a == b);

    return 0;
}
//outputs 10

我还尝试输出存储在变量 a 和 b 中的值,并为两者获得相同的值

#include <iostream>
using namespace std;

int main() 
{
    string d = "abc", e = "abc";
    char a[] = "abc", b[] = "abc";
    cout << (d == e);
    cout << (a == b);
    cout << "\n" << a << "\n";
    cout << b;

    return 0;
}
// outputs 10
//abc
//abc
4

2 回答 2

1

In C, std::string has a special operator== that actually compares the strings. Contrary to what you might read, std::strings are not equivalent to char arrays. Char arrays are essentially treated as pointers, so == compares the memory addresses, which are different, so the program will output 0.

于 2020-07-26T21:58:19.847 回答
1

为了比较 2 个 char 数组,您应该使用 strcmp,== 运算符比较指针地址而不是值本身。您还可以迭代数组并逐个元素进行比较。

于 2020-07-26T22:04:17.377 回答