c++ - 如何在 C++ 中将字符串传递给 const char*?

标签 c++ string vector char

我正在尝试在 C++ 中拆分 . 上的字符串,然后我需要将第一个拆分字符串传递给另一个接受 const char* key 的方法。但是每次我这样做,我总是得到一个异常(exception) -

下面是我的代码-

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);

下面是我总是得到的异常(exception) -

no matching function for call to AttributeMap::upsert(std::basic_string<char>&)

有什么我遗漏的吗?

最佳答案

使用c_str()获取指向“具有与存储在字符串中的数据等效的数据的空终止字符数组”的指针(引用自文档)。

attr_map.upsert(tokens[0].c_str()); //this won't throw an exception

关于c++ - 如何在 C++ 中将字符串传递给 const char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19412823/

相关文章:

c++ - 尝试从 vector 中获取 unique_ptr 元素后出错

c++ - 获取组中选中单选按钮的索引

c# - 在 C# 中不区分大小写地比较字符串

r - 从相似字符串的向量中获取唯一字符串

android - 无法将字符串传递给另一个 Activity

c++ - 在 C++ 中访问 boost::variant vector 的元素

c++ - 访问和打印用 new 初始化的 vector 的 vector

c++ - C++中抽象模板类中的类型名

c++ - double 值计算过程中错误计数增加

c++ - 如何将 UCHAR 转换为二进制