Wednesday, July 16, 2008

[VC++] How to Convert from CString to const char * and back

Dealing with VC++, this is only one of the painful conversions you could have to perform if you're working with CString and you need to pass down to some function (or whatever) a const char *.

Code-snippet follows (UNICODE on):

CString myString = "bollocks";

char stoneageBuffer[100];
//initialize your stoneage buffer
memset(stoneageBuffer,0,sizeof(stoneageBuffer));
sprintf(stoneageBuffer,"%S",myString);

//...

//back to CString
myString = stoneageBuffer;


Note that %S (and not %s) formatting type switches to the opposite type of character set (UNICODE if MBCS build and MBCS if UNICODE build).

3 comments:

Anonymous said...

This may someday give me nightmares.

Unknown said...

THANK YOU SO MUCH. I was about to pull my hair out.

Unknown said...

75% of C++ programmers are bald? Go figure why ...