【问题标题】:using strcmp between string array and 2d array string在字符串数组和二维数组字符串之间使用 strcmp
【发布时间】:2022-01-09 16:26:22
【问题描述】:

我需要在我输入的二维数组中搜索一个单词,但是当我使用 strcmp 函数时,我有一个错误“No Matching function for call to 'strcmp'

bool checkIfSameMedicine (char str1[], char str2[][MAXSIZE])
{
    for (int i = 0; i <= 3; i++)
    {
        if (strcmp(str2, str1))
        {
            return true;
        }
        return false;
    }
}

【问题讨论】:

  • strcmp 如果两个字符串都匹配则返回 0

标签: c++ multidimensional-array c-strings strcmp function-definition


【解决方案1】:

你至少要写

for (int i = 0; i <= 3; i++)
{
    if (strcmp(str2[i], str1) == 0)
    {
        return true;
    }
}
return false;

虽然由于使用了幻数3,代码看起来不太好。

函数应该像这样声明和定义

bool checkIfSameMedicine( const char str2[][MAXSIZE]), size_t n, const char str1[] )
{
    size_t i = 0;

    while ( i != n && strcmp( str2[i], str1 ) != 0 ) ++i;

    return n != 0 && i != n;
}

【讨论】:

  • 我更改了第一个代码并添加了一个定义而不是 3,我无法理解你编写的第二个函数,因为我对 c++ 很陌生,希望你能解释一下:)
  • @ShakedBarel 在第二个函数中,将二维数组 str2 的每个元素与存储在数组 str1 中的字符串进行比较。如果没有找到这样的元素,那么 i 将等于 n。如果找到这样的元素,则 i != n.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
  • 2016-05-06
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
  • 2021-12-07
相关资源
最近更新 更多