I'm using VS2012/C++, I need to convert a std::string to char * and I can't find any material online giving any guidance on how to go about doing it.
Any code examples and advice will be greatly appreciated.
Use
std::string bla("bla");
char* blaptr = &bla[0];
This is guaranteed to work since C++11, and effectively worked on all popular implementations before C++11.
If you need just a const char*
, you can use either std::string::c_str()
or std::string::data()
¡║½½½½½½½½½½½½½½EL)¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■B¶↑h4ë¡║
char*
buffer of the string is perfectly fine and the prime way of calling e.g. Win32 API functions without allocating arrays of char
yourself. What you have to do, is make sure you allocate enough space in the string
. As for "proof", see this answer. If quotes from the standard plus logical reasoning cannot prove this for you, I give up. Also: stop using strtok
, especially if you have std::string
with its numerous find
functions and std::stringstream
.
const char*
wouldn't it? But I'm guessing that's probably good enough.