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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It won’t automatically convert (thank god). You’ll have to use the method
c_str()to get the C string version..c_str()returns aconst char *. If you want a non-constchar *, use.data():Some other options:
Copying the characters into a vector:
Then
cstr.data()will give you the pointer.This version copies the terminating
\0. If you don’t want it, remove+ 1or dostd::vector<char> cstr(str.begin(), str.end());.Copying into a manually allocated array: (should normally be avoided, as manual memory management is easy to get wrong)