[英]C++ error: cannot convert ‘std::basic_string<char>’ to ‘const char*’
I'm using a function to download a file. 我正在使用一个功能来下载文件。
void downloadFile(const char* url, const char* fname) {
//..
}
This is called like : 这叫做:
downloadFile("http://servera.com/file.txt", "/user/tmp/file.txt");
This working fine. 这工作正常。
But I want to change the URL to be a value from an array. 但我想将URL更改为数组中的值。 The array stores encrypted values which when decrypted are strings, so I get the issue error: cannot convert 'std::basic_string<char>' to 'const char*'
该数组存储加密的值,该值在解密时为字符串,因此出现问题error: cannot convert 'std::basic_string<char>' to 'const char*'
I've tried: 我试过了:
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");
and 和
downloadFile((decode(foo[5]).c_str()) + "filename.txt", "/user/tmp/file.txt");
which gives: error: invalid operands of types 'const char*' and 'const char [17]' to binary 'operator+'
给出: error: invalid operands of types 'const char*' and 'const char [17]' to binary 'operator+'
What am I doing wrong ? 我究竟做错了什么 ?
Thanks 谢谢
C-strings can't be concatenated with +
. C字符串不能与+
串联。
Use std::string::+
instead: 使用std::string::+
代替:
downloadFile((test + "filename.txt").c_str(), "/user/tmp/file.txt");
Note that c_str
only returns a pointer to the std::string
's internal character array, so it's valid only during the execution of the downloadFile
function. 请注意, c_str
仅返回指向std::string
内部字符数组的指针,因此它仅在执行downloadFile
函数期间有效。
Try this: 尝试这个:
downloadFile((decode(foo[5]) + "filename.txt").c_str(), "/user/tmp/file.txt");
The operator+ is not defined for char arrays. 没有为char数组定义operator +。
The main problem in your code is that you are trying to use operator+
to concatenate raw C strings (ie raw const char*
pointers, or raw char []
arrays), which doesn't work. 代码中的主要问题是,您试图使用operator+
连接原始C字符串 (即原始const char*
指针或原始char []
数组),但无法正常工作。
In C, you should use proper library functions (like strncat
or safer variants) to do that; 在C语言中,您应该使用适当的库函数(例如strncat
或更安全的变体)来执行此操作; but since you are using C++ , you can do better, and write easier code: just use a C++ string class , like std::string
. 但是由于您使用的是C ++ ,因此您可以做得更好,编写更简单的代码:只需使用C ++字符串类 ,例如std::string
。
In fact, the C++ standard library offers convenient overloads for operator+
that work with std::string
, so you can concatenate C++ strings in an easy, intuitive and safe way; 实际上,C ++标准库为使用std::string
operator+
提供了方便的重载,因此您可以通过简单,直观和安全的方式连接C ++字符串。 for example: 例如:
// 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.