c++ - 在 C++11 中,如何打印给定 Unicode 代码的字符?

标签 c++ unicode printing hex

我敢肯定这是一个愚蠢的问题,但是有没有一种直接的方法可以在给定十六进制代码的情况下在 C++ 中打印 Unicode 字符?例如:我知道 ❤ 的代码是 0x2764。有没有一种方法可以使用它的代码来打印它(通过 printf 或在流上)?

作为记录,我可以通过以下方式打印字符:

cout << "\u2764" << endl;

但这需要在编译时知道值而不是使用变量。

谢谢

最佳答案

从评论中我看到您使用的是 OS X,它使用 UTF-8 并且具有足够完整的 C++11 库 (libc++) 实现,以便以下工作。

#include <codecvt>  // wstring_convert, codecvt_utf8
#include <iostream> // cout

int main() {
  std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert;

  std::cout << convert.to_bytes(static_cast<char32_t>(0x2764)) << '\n';
}

这取决于控制台与 UTF-8 是否正常工作,而 OS X 则可以。

关于c++ - 在 C++11 中,如何打印给定 Unicode 代码的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18488332/

相关文章:

C++ 运算符重载和继承

c++ - 使用类绑定(bind)功能调用成员函数

android - 通过蓝牙打印机 AGPtEK SC28 打印图像

css - @page :first { margin: . .. } 在 Chrome 错误中?

c++ - 构建 shared_ptr 时遇到问题

c++ - 在 Windows 上玩 GCC 4.6

android - 如何立即在 TextView 中显示来自 Edittext 的文本?

python - 在 tkinter 标签 Python 中显示平方根符号

php - 如何通过 php 读取 Windows unicode 文件并将它们存储在 utf-8 数据库中?

excel - 以相同缩放打印两种不同纸张尺寸的宏