By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,963 Members | 2,122 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,963 IT Pros & Developers. It's quick & easy.

How to convert wchar_t * to char *

P: 1
How can I convert a wchar_t * to char *? My code is something like that but it just get the first character:

wchar_t * filename= L"C:\\test";
char* c = (char*)filename;
Aug 6 '07 #1
Share this Question
Share on Google+
3 Replies


Expert 10K+
P: 11,448
How can I convert a wchar_t * to char *? My code is something like that but it just get the first character:

wchar_t * filename= L"C:\\test";
char* c = (char*)filename;
Welcome to the wonderful world of Unicode and the non ASCII world (most of the
real world actually). A wchar_t is a 16 bit codepoint. Most likely codepoints are
stored in little endian order on your machine because you can read the first
'character' which happens to be the ASCII codepoint for an upper case C while
the hi byte equals zero.

Basically you can't just chop off the high byte from a wchar_t to get your char.
You have to decide how you want to encode those 16 bit codepoints to 8 bit
encoded bytes. I suggest UTF-8 for this.

Read all about it at the Unicode site.

best of luck and

kind regards,

Jos
Aug 6 '07 #2

P: 18
petzold,

you can try this code:
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. int main(void)
  5. {
  6.     char *str;
  7.  
  8.     wchar_t array[] = L"Hello World";
  9.  
  10.     wcstombs(str, array, 12);
  11.  
  12.     std::cout << str;
  13.  
  14. }
Kind regards...
Aug 6 '07 #3

P: 1
In the example above,
you must allocate memory for str array and memset it with zeros.

Expand|Select|Wrap|Line Numbers
  1. char *str = new char[12 + 1];
  2. memset( str, 0, 12 + 1);
  3. wchar_t array[] = L"Hello World";
  4. wcstombs(str, array, 12);
  5. std::cout << str;
  6. delete str;
Aug 5 '15 #4

Post your reply

Sign in to post your reply or Sign up for a free account.