我正在尝试使用wchar_t,char16_t和char32_t类型打印汉字,但无济于事。 [英] I'm trying to print a Chinese character using the types wchar_t, char16_t and char32_t, to no avail.

查看:147
本文介绍了我正在尝试使用wchar_t,char16_t和char32_t类型打印汉字,但无济于事。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 wchar_t 类型打印汉字 char16_t char32_t ,但没有成功(实时例如

I'm trying to print the Chinese character using the types wchar_t, char16_t and char32_t, without success (live example)

#include <iostream>
int main()
{
    char x[] = "中";            // Chinese character with unicode point U+4E2D
    char y[] = u8"中";
    wchar_t z = L'中';
    char16_t b = u'\u4e2d';
    char32_t a = U'\U00004e2d';

    std::cout << x << '\n';     // Ok
    std::cout << y << '\n';     // Ok
    std::wcout << z << '\n';    // ?? 
    std::cout << a << '\n';     // prints the decimal number (20013) corresponding to the unicode point U+4E2D
    std::cout << b << '\n';     //             "                    "                   "
}


推荐答案

自您正在Linux系统上运行测试,源代码为UTF-8,这就是为什么 x y 是相同的东西,这些字节由 std :: cout<<<<< x std :: cout << y ,并且当您查看网页时(或当您查看linux终端时),您会看到预期的字符。

Since you're running your test on a Linux system, source code is UTF-8, which is why x and y are the same thing. Those bytes are shunted, unmodified, into the standard output by std::cout << x and std::cout << y, and when you view the web page (or when you look at the linux terminal), you see the character as you expected.

std :: wcout<< z

std::ios::sync_with_stdio(false);
std::wcout.imbue(std::locale("en_US.utf8"));

在不与C取消同步的情况下,GNU libstdc ++会通过C IO流,该C IO流在同一位置上打印一个窄字符后再也不会打印宽字符LLVM libc ++看起来甚至可以同步工作,但是当然仍然需要注入灵感来告诉流如何将宽字符转换为发送到标准输出的字节。

without unsynching from C, GNU libstdc++ goes through C IO streams, which can never print a wide char after printing a narrow char on the same stream. LLVM libc++ appears to work even synched, but of course still needs the imbue to tell the stream how to convert the wide chars to the bytes it sends into the standard output.

要打印 b a ,则必须将它们转换为宽或窄;即使使用 wbuffer_convert 设置char32_t流也需要大量工作。看起来像这样:

To print b and a, you will have to convert them to wide or narrow; even with wbuffer_convert setting up a char32_t stream is a lot of work. It would look like this:

std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> conv32;
std::cout << conv32.to_bytes(a) << '\n';

将它们放在一起: http://coliru.stacked-crooked.com/a/a809c38e21cc1743

这篇关于我正在尝试使用wchar_t,char16_t和char32_t类型打印汉字,但无济于事。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆