Convert std::string to char*.

Apr 30, 2013 at 4:14am
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 Apr 30, 2013 at 4:21am
Apr 30, 2013 at 4:30am
string.c_str()
Apr 30, 2013 at 5:34am
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;

Apr 30, 2013 at 2:21pm
closed account (18hRX9L8)
Thank you Catfish4!
May 1, 2013 at 12:48am
closed account (18hRX9L8)
Oh wait, also, how would I convert char* to string?
May 1, 2013 at 12:59am
1
2
3
const char* foo = "Whatever";

string bar = foo;
May 1, 2013 at 1:03am
closed account (18hRX9L8)
Thanks Disch.
Topic archived. No new replies allowed.