Friday, October 24, 2008

[C++] convert std::string to const char * (and back)

Kind of a lousy-ass post but Straight to the point (with UNICODE on):

#include <string>
using namespace std;

//..

//from std::string to const char*
string originalStr("Bunny Colvin Kicks Ass");
const char* cnstCharPtr = str.c_str();

//the other way around
string convertedStr(cnstCharPtr); //as simple as this
 
I found myself googlin' this up a number of times and I always forgot everything soon enough since I don't use it often. I decided to post it as a reference for myself and to increase chances to find an answer for anyone else who might be looking for it.

Cheers

2 comments:

André said...

Yeah, it was pretty much the first page that google returned me for "c++ string to const char*", and it works =)

Unknown said...

@Andre

cool - I wonder how I got this on the first page without consulting one of those SEO snake oil salesman :)