使用 strcmp() 比较 c 样式字符数组时不匹配

Mismatch while comparing a c-style character array using strcmp()

本文关键字:字符 数组 不匹配 样式 strcmp 比较 使用      更新时间:2023-10-16

我是 c++ 的新手。我正在研究字符串比较。但是当我比较以下代码中给出的正确字符串时,它给了我错误的答案:

char string[100] = {"a"};
if (strcmp(string,"a")){
     cout<<"Matched";
}else{
     cout<<"Not Matched";
}

输出:

不匹配

请让我解决这个问题。

这将起作用:

#include <iostream>
#include <cstring>
int main() {
    char str[100] = "a";
    if (0 == strcmp(str,"a")){
        std::cout << "Matched" << std::endl;
    } else {
        std::cout << "Not Matched" << std::endl;
    }
    return 0;
}

因为,正如标准所说,如果返回值为 0,传递给 strcmp 函数的两个字符串的内容相等。

但是,如果您使用 C++,那么我强烈建议您使用std::string而不是 char 数组。

阅读文档,strcmp 不返回布尔值。

你想要

if (strcmp(string,"a") == 0){

鉴于其他答案,我想以C++提供解决方案,而不是使用古老的 C 结构。

在C++中,我们尽量避免使用C数组(type name[count](,而是使用std::vector<type>std::array<type, count>。特别是对于字符串,使用数组没有意义,因为我们有 std::stringstd::string_view .第一个包含数据的所有权,第二个不包含。它们在使用上都很直观,因为简单的比较==返回真或假,而strcmp函数返回三态,其中 0(隐式转换为假(表示它们相等。

因此,在实践中,代码将如下所示。

#include <string>
#include <iostream>
int main(int, char**)
{
    std::string string = "a";
    if (string == "a")
        std::cout << "Matched";
    else
        std::cout << "Not Matched";
}

编译器资源管理器中的代码