char16_t printing

10.5k views Asked by At

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.

1

There are 1 answers

5
Howard Hinnant On BEST ANSWER

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';
}