C ++错误:无法将'std :: basic_string <char>'转换为'const char *'

时间:2016-02-10 15:09:22

标签: c++ string string-concatenation

我正在使用一个函数来下载文件。

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+’

我做错了什么?

由于

3 个答案:

答案 0 :(得分:5)

C字符串无法与+连接。

改为使用std::string::+

downloadFile((test + "filename.txt").c_str(), "/user/tmp/file.txt");

请注意,c_str仅返回指向std::string内部字符数组的指针,因此它仅在执行downloadFile函数期间有效。

答案 1 :(得分:2)

试试这个:

downloadFile((decode(foo[5]) + "filename.txt").c_str(), "/user/tmp/file.txt");

没有为char数组定义operator +。

答案 2 :(得分:1)

您的代码中的主要问题是您尝试使用operator+来连接原始 C字符串(即原始const char*指针或原始char []数组),它不起作用。

在C中,你应该使用适当的库函数(如strncat或更安全的变体)来做到这一点;但由于您使用的是 C ++ ,您可以做得更好,并编写更简单的代码:只需使用 C ++字符串类,例如{{1} }。

事实上,C ++标准库为std::string提供了与operator+一起使用的方便重载,因此您可以以简单,直观和安全的方式连接C ++字符串;例如:

std::string