In this article, we will discuss different ways to convert a string to const char* in C++.
Table Of Contents
Method 1: Using string::c_str() function
In C++, the string class provides a member function c_str(). It returns a const char pointer to the null terminated contents of the string. We can call this function to get a const char* to the characters in the string. Let’s see an example,
#include <iostream> #include <string> int main() { std::string sampleText = "This is a sample text"; // Convert string to const char* const char* textPtr = sampleText.c_str(); std::cout << textPtr << std::endl; return 0; }
Output:
This is a sample text
It converted a string to a const char pointer in C++.
Frequently Asked:
Method 2: Using string::data() function
In C++, the string class provides a member function data(). It returns a const pointer, pointing to the internal contents os string. So, we can use this to get a const char* to the characters in the string. Let’s see an example,
#include <iostream> #include <string> int main() { std::string sampleText = "This is a sample text"; // Convert string to const char* const char* textPtr = sampleText.data(); std::cout << textPtr << std::endl; return 0; }
Output:
This is a sample text
It converted a string to a const char pointer in C++.
Method 3: Using [] operator
If you are using the latest compiler of C++ i.e. C++11 onwards, then you can directly take the address of first character of string i.e. &strObj[0]
. As, from C++11 onwards,
std::string does the contiguous memory allocation for characters. So, we can just fetch the address of first character, and assign it to a const char pointer. Let’s see an example,
Best Resources to Learn C++:
#include <iostream> #include <string> int main() { std::string sampleText = "This is a sample text"; // Convert string to const char* const char* textPtr = &sampleText[0]; std::cout << textPtr << std::endl; return 0; }
Output:
This is a sample text
It converted a string to a const char pointer in C++.
Summary
We learned about three different ways to convert a string into const char* in C++. Thanks.