. Advertisement .
..3..
. Advertisement .
..4..
I have the following cpp code, but I do not know how to find the correct result. Why has this problem occurred, and how can it be solved? This is the code I am running:
stringstream data;
char *addr=NULL;
strcpy(addr,retstring().c_str());
//more code
printfunc(num,addr,data.str().c_str());
void Printfunc(int a, char *loc, char *stream)
This is the error text I receive:
invalid conversion from 'const char*' to 'char*'.
initializing argument 3 of 'void Printfunc(int, char*, char*)'on argument 3 of the function
The cause:
string:
data.str().c_str()
returns achar const*
, butPrintfunc()
needschar*
s. This is the reason of the error. It doesn’t alter the arguments, but prints them or names a file.This is why you might want to change your declaration.
Solution:
Alternativities include changing the
char const*
to achar*
, but it is better to fix the declaration.string::c.str()
returns a string with typeconst char *
, as seen thereA quick fix: try casting
printfunc(num,addr,(char *)data.str().c_str())
;Although the above might work, it’s not a well-defined behavior and is potentially dangerous.
This is a better solution: Use templates