using a string in a function.

Hi
I want to create a variable called path which contains a fixed path.

eg: string path = "/home/tom/";

and then calling a function save the file using `path` and a new file name

downloadFile("http://servera.com/file.txt", path+"filename.txt");

When I try and complie it I get:

test.cpp: In function ‘int main()’:
test.cpp:56:91: error: cannot convert ‘std::basic_string<char>’ to ‘const char*’ for argument ‘2’ to ‘void downloadFile(const char*, const char*)’


The function downloadFile is:

1
2
3
void downloadFile(const char* url, const char* fname) {
blah blah blah
}


and works if I remove path from the second argument.

Any idea how I can get this to work ?

Thanks :)
Path is a string. You're passing that string to a function which takes a const char* fname.

std::string != const char*
Last edited on
Thanks for the quick reply.

How do I set path as a const char* instead of a string ?
and then use it to provide the path to the destination file ?

thanks
It's pretty weird that you don't know that but, you just change the type from string to const char*.

const char* path = "/home/tom/";
Last edited on
I would separate the "combination" from the function call something like:

1
2
3
string path = "/home/tom/";
string new_path = path + "filename.txt";
downloadFile("http://servera.com/file.txt", new_path.c_str()); 
Last edited on
Thanks for the replies.

Setting const char* path = "/home/tom/"; and using it as :

downloadFile("http://servera.com/file.txt", path+"filename.txt");


results in

test.cpp: In function ‘int main()’:
test.cpp:56:51: error: invalid operands of types ‘const char*’ and ‘const char [39]’ to binary ‘operator+’


I'd prefer not to separate the combination as I plan to use path multiple times when downloading different files.

Any way I can do this ?
Thanks

I am very new to this !
I'd prefer not to separate the combination as I plan to use path multiple times when downloading different files.


So what is stopping you? I didn't change the value of path, I used a different variable name that had the combined path.

By the way you can't use the addition operator to combine C-strings.
Thanks - Now I've got the time to actually sit down and look at this I can see what you mean.

I now have this working and it has downloaded the files to the correct locations with the correct names.

Thanks :D
Perhaps:

downloadFile("http://servera.com/file.txt", path+std::string("filename.txt"));
No, remember downloadFile() expects a C-string. So perhaps:
downloadFile("http://servera.com/file.txt", (path + "filename.txt").c_str());

However IMO this is hard to read because of all the required parentheses.
jlb: Of course, you're right, but I thought it was the other way around.... I really don't touch C-strings for many years and code in C++ for around 10. Even main arguments are parsed to avoid these issues.
Topic archived. No new replies allowed.