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.
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.
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.
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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With