0

我正在尝试.在 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>&)

有什么我想念的吗?

4

2 回答 2

2

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

attr_map.upsert(tokens[0].c_str()); //this won't throw an exception
于 2013-10-16T20:11:02.327 回答
0

你应该使用string::c_str

attr_map.upsert(tokens[0].c_str())
                        //^^^

您可以查看参考以获取有关c_str()功能的详细信息。

您收到错误是因为upsert函数期望const char*,但您正在传递std::string,类型不匹配。

于 2013-10-16T20:11:46.193 回答