Sign in to follow this  
Perferati

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this