如何在C++中将字符串传递给常量字符*

How to pass a string to const char* in C++?

本文关键字:常量 字符 字符串 C++      更新时间:2023-10-16

我正在尝试在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,类型不匹配。