How to convert a std::string to const char* or char* in C++?


In this section, we will see how to convert C++ string (std::string) to const char* or char*. These formats are C style strings. We have a function called c_str(). This will help us to do the task. 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.

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

const char* c_str() const;

This function 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. If an exception is thrown, there are no changes in the string.

Example Code

 Live Demo

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

int main () {
   std::string str ("Please divide this sentence 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;
}

Output

Please
divide
this
sentence
into
parts

Updated on: 30-Jul-2019

900 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements