Convert std::string to const char* in C++
This post will discuss how to convert a std::string to const char* in C++. The returned pointer should point to a char array containing the same sequence of characters as present in the string object and an additional null terminator (‘\0’ character) at the end.
1. Using string::c_str function
We can easily get a const char* from the std::string in constant time with the help of the string::c_str function. The returned pointer is backed by the internal array used by the string object, and if the string object is modified, the returned pointer will also be invalidated.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <string> int main() { std::string str = "std::string to const char*"; const char *c = str.c_str(); std::cout << c; return 0; } |
Output:
std::string to const char*
2. Using string::data function
We can also call the string::data function on a std::string object to get const char*. This function works exactly like the string::c_str.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <string> int main() { std::string str = "std::string to const char*"; char const *c = str.data(); std::cout << c; return 0; } |
Output:
std::string to const char*
3. Using contiguous storage of C++11
We know that C++11 guarantees std::string‘s memory allocation to be contiguous. So, we can get a pointer to the underlying char[] array behind std::string by invoking &str[0] or &*str.begin(). This approach will not work with C++98/03 standard.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <string> int main() { std::string str = "std::string to const char*"; const char* c = &str[0]; std::cout << c; return 0; } |
Output:
std::string to const char*
That’s all about converting std::string to const char in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)