Convert std::string to char*.

closed account (18hRX9L8)
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;

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

string bar = foo;
closed account (18hRX9L8)
Thanks Disch.
Topic archived. No new replies allowed.