std::string to char*

user1598585 picture user1598585 · Sep 8, 2011 · Viewed 940k times · Source

I want to convert a std::string into a char* or char[] data type.

std::string str = "string";
char* chr = str;

Results in: “error: cannot convert ‘std::string’ to ‘char’ ...”.

What methods are there available to do this?

Answer

orlp picture orlp · Sep 8, 2011

It won't automatically convert (thank god). You'll have to use the method c_str() to get the C string version.

std::string str = "string";
const char *cstr = str.c_str();

Note that it returns a const char *; you aren't allowed to change the C-style string returned by c_str(). If you want to process it you'll have to copy it first:

std::string str = "string";
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());
// do stuff
delete [] cstr;

Or in modern C++:

std::vector<char> cstr(str.c_str(), str.c_str() + str.size() + 1);