使用 strcmp() 比较 c 样式字符数组时不匹配
Mismatch while comparing a c-style character array using strcmp()
我是 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::string
和 std::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";
}
编译器资源管理器中的代码
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?