How to convert wchar_t * to char *

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • petzold
    New Member
    • Aug 2007
    • 1

    How to convert wchar_t * to char *

    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 ;
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by petzold
    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

    Comment

    • afraze
      New Member
      • Aug 2007
      • 18

      #3
      petzold,

      you can try this code:
      Code:
      #include <iostream>
      #include <cstdlib>
      
      int main(void)
      {
          char *str;
      
          wchar_t array[] = L"Hello World";
      
          wcstombs(str, array, 12);
      
          std::cout << str;
      
      }
      Kind regards...

      Comment

      • syncovery
        New Member
        • Aug 2015
        • 1

        #4
        In the example above,
        you must allocate memory for str array and memset it with zeros.

        Code:
        char *str = new char[12 + 1];
        memset( str, 0, 12 + 1);
        wchar_t array[] = L"Hello World";
        wcstombs(str, array, 12);
        std::cout << str;
        delete str;
        Last edited by syncovery; Aug 5 '15, 10:30 AM. Reason: code

        Comment

        Working...