Perro said:
Because there are other functions that need "char*" as input, so I get
errors when I do: str1.c_str()
I would like to convert a string to a char*, or a const char* to char*.
Any advice?
When some function need a 'char*' (as opposed to 'const char*') as an input,
this usually means one of two things:
1) The function needs to modify the data pointed by that 'char*' pointer. In
this can what you are trying to do is simply useless, because strings of
'std::string' type cannot be modified through the pointer returned by 'c_str()'.
Functions that modify the data pointed by 'char*' parameter are not compatible
with 'std::string' at all. The only safe way around is to convert the
'std::string' to a standalone modifiable zero-terminated C-style string, pass it
to the function and then convert the results back to 'std::string'.
2) The function parameter is declared improperly. In other words, the function
doesn't really need to modify the data, i.e. it doesn't really need a 'char*'
and a 'const char*' would work just as well. The better way to resolve the
problem in this case would be to change the function's parameter declaration
from 'char*' to the more appropriate 'const char*', assuming this is possible.
Otherwise, the 'const_cast' of 'c_str()' result to 'char*' type (mentioned by
others) would work, but it is rather ugly.