What is std::basic_string::c_str in C/C++?

The c_str() method converts a string to an array of characters with a null character at the end. The function takes in no parameters and returns a pointer to this character array (also called a c-string).

Syntax

your_string_variable.cstr();

Visual

The null character at the end of the array indicates the end of a c-string. This character is used to indicate the end of the string and does not get printed.

Code

The following code illustrates how a string is converted to a pointer that points to the beginning of a null-terminated array of characters.

The my_string1 variable stores a phrase, which is converted to a c-string in line 10. A for loop is then implemented in line 13 to traverse through the whole phrase and print the characters.

#include <iostream>
#include <string>
int main()
{
//message
std::string my_string1 = "Happy Learning at Educative!";
//convert to c-string using c_str()
std::string my_cstring = my_string1.c_str();
//print
for(int i =0; i<my_cstring.length();i++)
{
std::cout<<" character is "<<my_string1[i]<<"\n";
}
std::cout<<"my cstring is " <<my_cstring<<"\n";
}