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
Release: 2024-12-01 07:46:12
Original
829 people have browsed it

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();
Copy after login

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();
Copy after login

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);
    Copy after login

    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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template