Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 472
NoSenseEtAl Avatar asked Apr 10 '11 12:04

NoSenseEtAl


People also ask

What does char16_t do in C++?

In C++ programs, char16_t is a fundamental data type that can represent a 16-bit character type. This type could be used for UTF-16 characters. You can create a char16_t type with u'<character>', which is a literal for a single char16_t character.

What is char16?

char16_t is an unsigned integer type used for 16-bit wide characters and is the same type as uint_least16_t. uint_least16_t is the smallest unsigned integer type with width of at least 16 bits.


1 Answers

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';
}
like image 101
Howard Hinnant Avatar answered Oct 19 '22 02:10

Howard Hinnant