Convert std::string to char*.

Is there anyway to convert std::string to char*?

Like:
1
2
std::string x="hello world";
char* y=x;
Last edited on
string.c_str()
1
2
std::string x = "hello world";
char *y = x.c_str();

For this you apply the D3 rule: Don't Do Dat. Because when x "dies", so will y.

1
2
3
4
5
6
7
8
9
10
11
#include <cstring>
#include <string>

// ...

std::string x = "hello world";
char *y = new char[x.length() + 1]; // or
// char y[100];

std::strcpy(y, x.c_str());
delete[] y;

Thank you Catfish4!
Oh wait, also, how would I convert char* to string?
1
2
3
const char* foo = "Whatever";

string bar = foo;
Thanks Disch.
Topic archived. No new replies allowed.