strcmp(x, str) is wrong?

strcmp(x, str) is wrong?

本文关键字:is wrong str strcmp      更新时间:2023-10-16

作为C++的初学者,我在这一点上感到困惑了很长一段时间,程序是告诉字符串中每个单词的出现时间。

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
    string x;
    vector<string> str;
vector<int> t;
while (cin >> x)
{
    int k = 0;
    for (int j = 0; j != str.size(); j++)
    {
        if (strcmp(x,str[j]) == 0)
            t[j]++;
        k = 1;
    }
    if (k == 0)
    { 
        str.push_back(x);  
        t.push_back(1);     
    }  
}
for (int i = 0; i != str.size(); i++ )
{
    cout << str[i] << "   " << t[i] << endl;
}
return 0;
}

错误如下:

C++code3.3.cpp(17) : error C2664: 'strcmp' : cannot convert parameter 1 from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'const char *'
        No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

经过长时间的搜索,我在网上找不到任何结果。我该怎么解决这个问题?

如果x和y是C++字符串,那么只需说x == y。您正试图在C++对象上使用C函数strcmp

如果y是C样式字符串,那么相同的代码x == y也将起作用,因为C样式字符串将自动转换为C++样式字符串,但是在这种情况下,最好使用strcmp(x.c_str(), y) == 0,因为这样可以避免自动转换。

只有当x和y都是C风格的字符串时,才应该执行strcmp(x, y) == 0

错误是因为strcmp期望的const char*std::string不同。您可以在该字符串上检索调用方法c_str()的const char*:

if (strcmp(x.c_str(),y) == 0)

除此之外,"y"参数似乎没有在代码中声明。

X是一个字符串,strcmp比较const char*要将字符串转换为常量字符*,请使用

x.c_str ()

编译器需要const char*或可转换为const char*的东西。但是CCD_ 11不能隐式地转换为CCD_。

如果要使用strcmp,则必须使用方法c_str来获得const char*。但在您的情况下,可能最好使用==,它被重载以处理std::string。

jahhaj是对的,但如果您想在字符串上调用C函数,可以使用string_instance.c_str()将字符串作为const char *