Convert std::string to char* or char[]
Converting a std::string to a char* or char[] data type can be a common task in C , but it's worth noting that automatic conversion is not supported. To achieve this, the c_str() method can be used to obtain a C-style string representation of the std::string.
std::string str = "string"; const char *cstr = str.c_str();
The c_str() method returns a const char pointer, so if a non-const pointer is required, the data() method can be used instead:
char *cstr = str.data();
Alternative Options:
In addition to using c_str() and data(), there are other methods for converting std::string to char*:
Copying Characters into a Vector:
std::vector<char> cstr(str.c_str(), str.c_str() + str.size() + 1);
Note that this version copies the terminating null character ('
The above is the detailed content of How to Convert a std::string to a char* or char[] in C ?. For more information, please follow other related articles on the PHP Chinese website!