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

时间:2013-10-16 20:08:28

标签: c++ string vector char

我试图在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>&)

我有什么遗失的吗?

2 个答案:

答案 0 :(得分:2)

使用c_str()获取指向“以null结尾的字符数组的指针,其数据与存储在字符串中的数据相同”(引自文档)。

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

答案 1 :(得分:0)

您应该使用string::c_str

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

您可以查看参考资料,了解c_str()功能的详细信息。

您收到错误是因为upsert函数需要const char*,但您传递std::string,输入不匹配。