• Register
search
Log In

STL provides the function c_str(), so it is very clear that c_str() is a built-in function since STL is built-in. The function c_str() returns a pointer to an array that contains a null terminated sequence of characters (it means C-string). The sequence of characters represents the current value of the basic string object. Sequences of characters are the same as the make up value of the basic string object plus an additional terminating null-character at the end, included by this array.

Syntax

Const char* c_str() const;

In C++14 

Const char* c_str() const noexcept;

Note : This function does not accept any parameter.

 

Value returned

This function returns a pointer which is a constant null terminated to the character array storage of the string.

 

For example

// C++ code for illustration of 
// basic_string::c_str function 
#include <bits/stdc++.h> 
#include <string> 
using namespace std; 
  
int main() 
{ 
    // declare a example string 
    string s1 = "KODLOGS"; 
  
    // print the characters of the string 
    for (int i = 0; i < s1.length(); i++) { 
        cout << "The " << i + 1 << "th character of string " << s1 
             << " is " << s1.c_str()[i] << endl; 
    } 
} 


Output

The 1th character of string KODLOGS is K
The 2th character of string KODLOGS is O
The 3th character of string KODLOGS is D
The 4th character of string KODLOGS is L
The 5th character of string KODLOGS is O
The 6th character of string KODLOGS is G
The 7th character of string KODLOGS is S
posted Jun 22 in c++ 100 points