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

C++Server Side ProgrammingProgramming

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


raja
Published on 28-Feb-2018 11:22:03
Advertisements