gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:07:06 25 4
gpt4 key购买 nike

我正在尝试在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com