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


You can use the c_str() method of the string class to get a const char* with the string contents. 

example

#include<iostream>
using namespace std;

int main() {
   string x("hello");
   const char* ccx = x.c_str();
   cout << ccx;
}

Output

This will give the output −

hello

To get a char*, use the copy function.

Example

#include<iostream>
using namespace std;

int main() {
   string x("hello");

   // Allocate memory
   char* ccx = new char[s.length() + 1];

   // Copy contents
   std::copy(s.begin(), s.end(), ccx)
   cout << ccx;
}

Output

This will give the output −

hello


Updated on: 12-Feb-2020

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements