C++ – How to Convert std::string to const char* or char*

c++charstdstringstring

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

Best Answer

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.

Related Question