簡體   English   中英

如何在C ++中將字符串傳遞給const char *?

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

我正在嘗試拆分字符串. 在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 ,類型不匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM