Tuesday, August 10, 2010

C++: Parsing string to char*

Most of the time, standard C++ method required char* input instead of the comfortably used string. Using string is a lot easier and already coded with basic useful function like comparison (==, !=) or attachment (string1 + string2).

To convert a string into char*, you can use this method

string str = "hello, pandora";
char * cstr = new char[str.size() + 1];
strcpy(cstr, str.c_str());

Note that c_str() only treat the string as a char* without moving its pointer. You need to copy the result into a new pointer to have a brand new char*.

For a full reference, you can check here.

No comments: