# Converting from wchar_t to char*

## Recommended Posts

Perferati    138
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

##### Share on other sites
TheTroll    883
Why are you doing this? You do realize you are loosing information if you do that.

theTroll

##### Share on other sites
griffin2000    214
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).

##### Share on other sites
IFooBar    906
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.

##### Share on other sites
AsOne    326
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;

##### Share on other sites
Perferati    138
Thanks for all the help guys!

Perferati