Converting from wchar_t to char*
5 replies to this topic
Members - Reputation: 138
Posted 13 May 2006 - 06:26 AM
Hey all, Had some success earlier tracking down my problem (was using ANSII strings instead of the UNICODE which my program is set to) Now im having trouble converting from wchar_t to char* Thought a simple wcstombs(chPath, wString, sizeof(wString+1)); should work, but gives me a garbled mess...something I am clearly missing here. Could someone please give me some sample code on how to convert wchar_t to char*? Would be much appreciated. Perferati
Members - Reputation: 214
Posted 13 May 2006 - 06:35 AM
I beleive wchar is just unicode-16. So for valid ASCII text each char will be in the form 0x00AB, where 0xAB is a valid 8-bit ASCII char. If it is not in this form (e.g. your first byte !=0) then it does not map trivially to ASCII. This is how my conversion function works (and I have yet to have any problems).
Members - Reputation: 906
Posted 13 May 2006 - 06:55 AM
wchar_t* wstr = L"A wide character string.";
char* ascii = new char[wcslen(wstr) + 1];
wcstombs( ascii, wstr, wcslen(wstr) );
sizeof(swtr) will return either 4 or 8 depending on the size of a pointer. Because that's what it is - a pointer to wide characters. It's teh equivalunet of doing:
Which is not what you want, you need the number of characters that your string points to. For that use wcslen for wide chars and strlen for normal chars.