C++ error: cannot convert ‘std::basic_string<char>’ to ‘const char*’
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+’
我做错了什么?
谢谢
试试这个:
downloadFile((decode(foo[5]) + "filename.txt").c_str(), "/user/tmp/file.txt");
没有为字符数组定义运算符+。
C 字符串不能与 +
连接。
改用std::string::+
:
downloadFile((test + "filename.txt").c_str(), "/user/tmp/file.txt");
注意c_str
只是returns一个指向std::string
内部字符数组的指针,所以它只在downloadFile
函数执行期间有效。
代码中的主要问题是您试图使用 operator+
连接原始 C 字符串 (即原始 const char*
指针,或原始char []
个数组),这是行不通的。
在 C 中,您应该使用适当的库函数(如 strncat
或更安全的变体)来做到这一点;但由于您使用的是 C++,您可以做得更好,并编写 更简单的 代码:只需使用 C++ 字符串 class,喜欢std::string
.
事实上,C++ 标准库为 operator+
提供了与 std::string
一起使用的便捷重载,因此您可以以简单、直观和安全的方式连接 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");
我正在使用下载文件的功能。
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+’
我做错了什么?
谢谢
试试这个:
downloadFile((decode(foo[5]) + "filename.txt").c_str(), "/user/tmp/file.txt");
没有为字符数组定义运算符+。
C 字符串不能与 +
连接。
改用std::string::+
:
downloadFile((test + "filename.txt").c_str(), "/user/tmp/file.txt");
注意c_str
只是returns一个指向std::string
内部字符数组的指针,所以它只在downloadFile
函数执行期间有效。
代码中的主要问题是您试图使用 operator+
连接原始 C 字符串 (即原始 const char*
指针,或原始char []
个数组),这是行不通的。
在 C 中,您应该使用适当的库函数(如 strncat
或更安全的变体)来做到这一点;但由于您使用的是 C++,您可以做得更好,并编写 更简单的 代码:只需使用 C++ 字符串 class,喜欢std::string
.
事实上,C++ 标准库为 operator+
提供了与 std::string
一起使用的便捷重载,因此您可以以简单、直观和安全的方式连接 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");