This question already has answers here:
C++ if statements using strings not working as intended

(4个答案)


去年关闭。




我创建了一个二维的字符指针数组。我想用它来创建一个字典,如果变量ent是字典的一部分,则该单词的对应字典条目(如果存在)将被检索。我目前正在使用strcmp,但这仅仅是因为==运算符给了我很大的麻烦。我不确定为什么==运算符不会导致期望的结果。

我怀疑它可能与指针比较有关,因为我正在将一个字符串的指针与另一个字符串的指针进行比较,不一定是其内容。
#include <iostream>
#include <cstring>

int main() {
    char *dictionary[][2] {
        {"First","Monday"},
        {"Second","Tuesday"},
        {"Third","Wednesday"},
        {"Fourth","Thursday"},
        {"Fifth","Friday"},
        {"Sixth","Saturday"},
        {"Seventh","Sunday"},
        {"",""}
    };

    char ent[80] = "Sixth";

        for (int i{}; *dictionary[i][0]; i++) {
            if (!strcmp(dictionary[i][0], ent)) {
                std::cout << "Word found: " << ent
                          << " corresponds to: " << dictionary[i][1]
                          << std::endl;
                return 0;
            }
        }

    std::cout << ent << " not found." << std::endl;
    return 1;
}

我想用类似的东西替换if (!strcmp(dictionary[i][0], word))if (word == dictionary[i][0])并产生Word found: Sixth corresponds to Saturday
如果我不能使用==运算符执行此操作,是否可以通过使用指针但不依赖 header 的函数来执行此操作?

谢谢!

最佳答案

在if语句的条件下

if (word == dictionary[i][0])

比较字符串的第一个字符的地址。

在表达式中,具有极少数异常(exception)的数组(例如,在sizeof运算符中使用它们)将隐式转换为指向其第一个元素的指针。

例如,如果您将编写这样的if语句
if ( "hello" == "hello" ) { /*...*/ }

然后,表达式将根据编译器选项的计算结果为truefalse,该选项指定在内部将相等的字符串文字存储为一个字符串还是多个单独的字符串。

您可以以这样的方式定义字典,使其元素类型为std::string。在这种情况下,您可以使用等于运算符==。

在这种情况下,您可以将std::string类型的对象与包含字符串的字符数组进行比较,因为字符数组将隐式转换为std::string类型的临时对象。

10-04 12:06
查看更多