2

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. 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*’

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

What am I doing wrong ?

Thanks

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
Rocket
  • 1,065
  • 2
  • 21
  • 44
  • 1
    You are trying to add pointers (which obviously isn't what you want to do). You should construct the whole path in a `std::string` variable first, and then pass `c_str()` to the `downloadFile()` function. – πάντα ῥεῖ Feb 10 '16 at 15:12

3 Answers3

5

C-strings can't be concatenated with +.

Use std::string::+ instead:

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.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
2

Try this:

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

The operator+ is not defined for char arrays.

ul90
  • 762
  • 3
  • 8
1

The main problem in your code is that you are trying to use operator+ to concatenate raw C strings (i.e. raw const char* pointers, or raw char [] arrays), which doesn't work.

In C, you should use proper library functions (like strncat or safer variants) to do that; but since you are using C++, you can do better, and write easier code: just use a C++ string class, like 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; 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");
Mr.C64
  • 41,637
  • 14
  • 86
  • 162