Re: How to convert from string to char*?
Lorry Astra wrote:
1. How to convert from string to char*? I use c_str() of string, but it
returns "const char*" instead of char*;
The question is what you want to do with that char*.
If you have a poorly written or old function that takes a read-only
char* input, but without the const keyword, just use the &str[0] expression:
void OldCCall(char* filename);
// some old 3rd party API call, improperly omitting the const keyword
void ModernCall(const std::string& filename)
{
std::string filename_tmp(filename);
OldCCall(&filename_tmp[0]);
}
This technique is mostly useful if you are certain that OldCCall treats
the string as read-only. If OldCCall tries to write beyond
filename.size(), you will get into trouble. I prefer this solution to
const_cast, because I have no way of knowing if OldCCall actually writes
its input (for whatever sloppy reason). If an API call omits the const
keyword, assume the worst.
You can also use string just as a memory buffer:
std::string buff(length, 0);
char* s = &buff[0];
And then you can write to this buffer, but you can't write more than
length characters/bytes to it. Just remember that 0-terminating this
buffer early won't make the string's size smaller -- buff.size() is
always length in this example. You would use strlen(buff.c_str()) to get
the size of the contained C-string.
Tom