将 2D 字符串数组与字符串C++进行比较

Comparing 2d string array to a string C++

本文关键字:字符串 C++ 比较 2D 数组      更新时间:2023-10-16

我有一个 2d 字符串数组和一个我想比较的字符串,但 strcmp 不起作用,除非我将字符串转换为 (const char*),这导致我出现 seg 错误。

目前我的代码简化为:

string dog;
cin >> dog;
string cat[10][10];
//The cat array is then filled with values through cin
//This is the troublesome part 
if (strcmp(cat[4][3].c_str(), dog[0]) == 0) {
//do stuff
}

使用 &dog[0] 获取狗的地址是有效的,但随后我得到了放入 dog 的整个单词,而不仅仅是我想要的字母。

有什么解决方法吗?

您正在使用具有重载operator==的C++ std::string,因此您根本不需要strcmp。 如果你想看看两个string是否相等,你可以做cat[4][3] == dogcat[4][3]是一个std::string,所以你可以直接将其与dog进行比较。

如果你只是想比较第一个字符,你可以做cat[4][3][0] == dog[0]

弦猫[10]

[10];

然后通过 cin 填充 cat 数组

的值

这是麻烦的部分

if (strcmp(cat[4][3].c_str(), dog[0]) == 0) {
//do stuff
}

这就是我认为正在发生的事情。你想创建一个字符串猫[10],而不是字符串猫[10][10]

现在让我解释一下。 //cat[0] =这不需要"字符串",它需要一个包含 10 个字符串的数组 [不是我认为是您所期望的 10 个字符的字符串)

cat[0][0] = "hello world";
//to access "h" letter you would need to use
cat[0][0][0] and then do
if (cat[0][0][0] != dog[0])

我认为这是您想要做的(比较一个字母),否则只需比较字符串

if (cat[0][0] != dog) //note that this is a case sensitive