convert string to char* in cpp code example

Example 1: convert string to char c++

// "std::string" has a method called "c_str()" that returns a "const char*"
// pointer to its inner memory. You can copy that "const char*" to a variable
// using "strcpy()".

std::string str = "Hello World";
char buffer[50];

strcpy(buffer, str.c_str());

std::cout << buffer;	//Output: Hello World

//POSTED BY eferion ON STACK OVERFLOW (IN SPANISH).

Example 2: c++ string to char array

const char *array = tmp.c_str(); //For const char array
char *array = &tmp[0]; // If you need to modify the array

Tags:

Misc Example