std::string to char*

7501 단어
Q: 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?
A: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;

좋은 웹페이지 즐겨찾기