C++ String Library - c_str



Description

It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.

Declaration

Following is the declaration for std::string::c_str.

const char* c_str() const;

C++11

const char* c_str() const noexcept;

C++14

const char* c_str() const noexcept;

Parameters

none

Return Value

It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.

Exceptions

if an exception is thrown, there are no changes in the string.

Example

In below example for std::string::c_str.

#include <iostream>
#include <cstring>
#include <string>

int main () {
   std::string str ("Please divide this sentance into parts");

   char * cstr = new char [str.length()+1];
   std::strcpy (cstr, str.c_str());

   char * p = std::strtok (cstr," ");
   while (p!=0) {
      std::cout << p << '\n';
      p = std::strtok(NULL," ");
   }

   delete[] cstr;
   return 0;
}

The sample output should be like this −

Please
divide
this
sentance
into
parts
string.htm
Advertisements