如何在C++中将字符串传递给常量字符*
How to pass a string to const char* in C++?
我正在尝试在C++中拆分.
上的字符串,然后我需要将第一个拆分的字符串传递给另一个接受const char* key
的方法..但每次我这样做,我总是得到一个例外——
下面是我的代码 -
istringstream iss(key);
std::vector<std::string> tokens;
std::string token;
while (std::getline(iss, token, '.')) {
if (!token.empty()) {
tokens.push_back(token);
}
}
cout<<"First Splitted String: " <<tokens[0] << endl;
attr_map.upsert(tokens[0]); //this throws an exception
}
下面是 AttributeMap.hh 文件中的 upsert 方法 -
bool upsert(const char* key);
下面是我总是得到的例外——
no matching function for call to AttributeMap::upsert(std::basic_string<char>&)
我缺少什么吗?
使用 c_str()
获取指向"以 null 结尾的字符数组,其数据等同于字符串中存储的数据"的指针(引用自文档)。
attr_map.upsert(tokens[0].c_str()); //this won't throw an exception
你应该使用 string::c_str
attr_map.upsert(tokens[0].c_str())
//^^^
您可以查看参考以获取有关c_str()
函数的详细信息。
您收到错误是因为upsert
函数需要const char*
,但您传递的是std::string
,类型不匹配。
相关文章:
- 如何循环访问常量字符**?
- constexpr 函数获取常量字符*
- 如何计算常量字符**中的总字符数?
- QDial:如何将 int 值传递给需要常量字符*的 Qfile?
- 为什么 std::string_view 比常量字符*快?
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- 在编译时将常量字符* 转换为常量 char_type*
- 将字符串数组传递给接受常量字符**的函数
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 字符串强制转换为常量字符*
- 使用常量字符*时退出代码 139
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法<string>从"常量字符 []"转换为<类名>
- 初始化常量字符* 数组
- 常量字符*的性质是什么?
- C++ 获取向量中常量字符* [ ] 的长度
- 无法将参数 1 从 WCHAR 转换为常量字符 *
- 如何在 c++ 中将向量转换为<string>常量字符* const*?
- C++将常量字符* 指针数组传递给对象