Home >Backend Development >C++ >How to Convert a std::string to a char* or char[] in C ?

How to Convert a std::string to a char* or char[] in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-01 07:46:12831browse

How to Convert a std::string to a char* or char[] in C  ?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn