Search code examples
printingc++11coutwchar-tchar16-t

char16_t printing


Recently I had a problem with porting a Windows application to Linux because of the wchar_t size difference between these platforms. I tried to use compiler switches, but there were problems with printing those characters (I presume that GCC wcout thinks that all wchar_t are 32bit).

So, my question: is there a nice way to (w)cout char16_t? I ask because it doesn't work, I'm forced to cast it to wchar_t:

cout << (wchar_t) c;

It doesn't seem like a big problem, but it bugs me.


Solution

  • Give this a try:

    #include <locale>
    #include <codecvt>
    #include <string>
    #include <iostream>
    
    int main()
    {
        std::wstring_convert<std::codecvt_utf8_utf16<wchar_t> > myconv;
        std::wstring ws(L"Your UTF-16 text");
        std::string bs = myconv.to_bytes(ws);
        std::cout << bs << '\n';
    }