![](/img/trans.png)
[英]Error cannot convert 'std::string {aka std::basic_string<char>}' to 'char' in assignment - C++
[英]C++ error: cannot convert ‘std::basic_string<char>’ to ‘const char*’
我正在使用一個功能來下載文件。
void downloadFile(const char* url, const char* fname) {
//..
}
這叫做:
downloadFile("http://servera.com/file.txt", "/user/tmp/file.txt");
這工作正常。
但我想將URL更改為數組中的值。 該數組存儲加密的值,該值在解密時為字符串,因此出現問題error: cannot convert 'std::basic_string<char>' to 'const char*'
我試過了:
string test = decode(foo[5]);
const char* t1= test.c_str();
downloadFile(t1 "filename.txt", "/user/tmp/file.txt");
downloadFile(t1 + "filename.txt", "/user/tmp/file.txt");
和
downloadFile((decode(foo[5]).c_str()) + "filename.txt", "/user/tmp/file.txt");
給出: error: invalid operands of types 'const char*' and 'const char [17]' to binary 'operator+'
我究竟做錯了什么 ?
謝謝
C字符串不能與+
串聯。
使用std::string::+
代替:
downloadFile((test + "filename.txt").c_str(), "/user/tmp/file.txt");
請注意, c_str
僅返回指向std::string
內部字符數組的指針,因此它僅在執行downloadFile
函數期間有效。
嘗試這個:
downloadFile((decode(foo[5]) + "filename.txt").c_str(), "/user/tmp/file.txt");
沒有為char數組定義operator +。
代碼中的主要問題是,您試圖使用operator+
連接原始C字符串 (即原始const char*
指針或原始char []
數組),但無法正常工作。
在C語言中,您應該使用適當的庫函數(例如strncat
或更安全的變體)來執行此操作; 但是由於您使用的是C ++ ,因此您可以做得更好,編寫更簡單的代碼:只需使用C ++字符串類 ,例如std::string
。
實際上,C ++標准庫為使用std::string
operator+
提供了方便的重載,因此您可以通過簡單,直觀和安全的方式連接C ++字符串。 例如:
// Build your URL string
std::string test = decode(foo[5]);
std::string url = test + "filename.txt";
// Use std::string::c_str() to convert from C++ string
// to C raw string pointer const char*
downloadFile(url.c_str(), "/user/tmp/file.txt");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.