简体   繁体   中英

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

I am trying to split a string on . in C++ and then the first splitted string I need to pass into another method which accepts const char* key .. But everytime I do, I always get an exception -

Below is my code -

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
}

Below is the upsert method in AttributeMap.hh files -

bool upsert(const char* key);

And below is the exception I always get -

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

Is there anything I am missing?

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

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

You should use string::c_str

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

You can check the reference for details on c_str() function.

You are getting the error because upsert function expects const char* , but you are passing std::string , type mismatch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM