Converting from wchar_t to char*

Started by
4 comments, last by Perferati 17 years, 11 months ago
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
Advertisement
Why are you doing this? You do realize you are loosing information if you do that.

theTroll
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).
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:

sizeof(wchar_t*);

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.

[size=2]aliak.net
I'm an idiot, I thought you wanted wchar_t* to char* ... I deleted the rest of my post.

EDIT: This works.
wchar_t wc = 'H';char c[2];wctomb(c, wc);cout << c;
Thanks for all the help guys!

Perferati

This topic is closed to new replies.

Advertisement