如何打印 unicode 代码点

How to print unicode codepoint?

本文关键字:unicode 代码 打印 何打印      更新时间:2023-10-16

如何在 Linux 上以 C++ (gcc/clang) 将 unicode 代码点打印为 unicode 字符?假设我有这样的东西:

typedef uint32_t codepoint;
codepoint cp = somefunction();

如何将 cp 打印为单个 unicode 字符?我有en_US。UTF-8 语言环境。

我已经搜索过了,我试过:wcout,wstring,wchar_t,setlocale,codecvt(gcc中不存在)。

GNU中的std::wcout有点怪癖:虽然与C stdio同步,但C++和C I/O子系统都需要单独本地化:

所以要么不同步

#include <iostream>
#include <cstdint>
#include <locale>
int main()
{
    std::uint32_t n = 0x98A8;
    std::wcout.sync_with_stdio(false);
    std::wcout.imbue(std::locale("en_US.utf8"));
    std::wcout << wchar_t(n) << 'n';
}

http://coliru.stacked-crooked.com/a/13b718ae11fa539e

或同时本地化两者

#include <iostream>
#include <cstdint>
#include <locale>
#include <clocale>
int main()
{
    std::uint32_t n = 0x98A8;
    std::setlocale(LC_ALL, "en_US.utf8");
    std::wcout.imbue(std::locale("en_US.utf8"));
    std::wcout << wchar_t(n) << 'n';
}

http://coliru.stacked-crooked.com/a/80b7d4547e1184ad