strcmp(x, str) is wrong?
strcmp(x, str) is wrong?
作为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 *
相关文章:
- Why is UINT32_MAX + 1 = 0?
- C++错误:"error: int aaa::bbb is protected within this context"
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- Is !NaN not a NaN?
- Directx 11 - CompileFromFile() is not compiling
- Centos7 g++ "to_string is not in a member of std"
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- Where is std::hardware_destructive_interference_size?
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- What is unordered_set in C++
- 你如何理解"std: :forward is just syntactic sugar"?这是真的吗?
- C++ "error: use of overloaded operator '*' is ambiguous"似乎只有一场比赛
- C++ is calculating wrong
- Is it good to use SDL_PIXELFORMAT_UNKNOWN?
- reference_wrapper导致"incomplete type is not allowed"
- Is std::is_trivially_copyable wrong?
- "Static polymorphism with Qt signal/slot: What is wrong?"
- 如何解决'path is wrong'编译错误,包括 GTKmm 3.0
- strcmp(x, str) is wrong?