比较 std::字符串与常量 vs 比较 char 数组与常量 In C++.

Comparing std::string with constants vs comparing char arrays with constants In C++

本文关键字:比较 常量 In C++ 数组 vs std 字符串 char      更新时间:2023-10-16

我正在尝试进行一些文本冒险以掌握C++。

cin >> keyboard1;  
if ((keyboard1 == "inv")inventory(inv);  

如果 keyboard1 是一个字符串,这将起作用,但如果它是一个字符数组,这将不起作用,这是因为我没有在常量末尾包含 null 吗?

假设您的代码如下:

int main(int argc, char *argv[])
{
    std::string s;
    std::cin >> s;
    std::cout << s << std::endl;
    if (s == "inv") {
        std::cout << "Got it" << std::endl;
    }
    return 0;
}

由于 stl 类string重写==运算符的方式,因此这按预期工作。

您不能期望以下代码正常工作:

int main(int argc, char *argv[])
{
    char *s = (char *)calloc(10, sizeof(char));
    std::cin >> s;
    std::cout << s << std::endl;
    if (s == "inv") {
         std::cout << "Got it" << std::endl;
    }
    return 0;
}

因为您正在比较 s,这是字符串开始到常量字符串的地址(顺便说一下,编译器会自动以 null 结尾)。

你应该使用 strcmp 来比较 "c 字符串":

int main(int argc, char *argv[])
{
    char *s = (char *)calloc(10, sizeof(char));
    std::cin >> s;
    std::cout << s << std::endl;
    if (strcmp(s, "inv") == 0) {
        std::cout << "Got it" << std::endl;
    }
    return 0;
}

这行得通。

不,它不起作用的原因是您将比较表示每个字符串的内存地址。请改用strcmp/wcscmp

比较字符串和常量工作的原因是字符串类将定义一个相等运算符(例如 bool StringClass:operator==(const char* pszString))。

如果keyboard1是一个char数组,那么if (keyboard1 == "inv")正在执行一个简单的指针比较(两者都变成char*)。

keyboard1是字符串时,如果存在operator==(cosnt string&, const char*),它可以调用,否则,如果字符串具有非显式构造函数string(const char *s),则常量"inv"将被隐式转换为字符串对象,并operator==(const string&,const string&)应用。