HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppCritical

How to convert a std::string to const char* or char*

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howconststdconvertcharstring

Problem

How can I convert an std::string to a char or a const char?

Solution

If you just want to pass a std::string to a function that needs const char *, you can use .c_str():

std::string str;
const char * c = str.c_str();


And if you need a non-const char *, call .data():

std::string str;
char * c = str.data();


.data() was added in C++17. Before that, you can use &str[0].

Note that if the std::string is const, .data() will return const char * instead, like .c_str().

The pointer becomes invalid if the string is destroyed or reallocates memory.

The pointer points to a null-terminated string, and the terminator doesn't count against str.size(). You're not allowed to assign a non-null character to the terminator.

Code Snippets

std::string str;
const char * c = str.c_str();
std::string str;
char * c = str.data();

Context

Stack Overflow Q#347949, score: 1311

Revisions (0)

No revisions yet.