1

I am sure this is a dumb question, but is there a straightforward way to print a Unicode character in C++ given its hex code? For instance: I know that the code for ❤ is 0x2764. Is there a way I can use its code to print it (either via printf or on a stream)?

For the record, I can print the character by writing:

cout << "\u2764" << endl;

but that requires knowing the value at compile time rather than using a variable.

Thanks

4

2 回答 2

2

从评论中,我看到您使用的是 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';
}

这取决于控制台与 OS X 的 UTF-8 一起正常工作。

于 2013-08-28T18:43:05.673 回答
0

一定要输出wchar_t到流。

#include <iostream>

std::wcout << static_cast<wchar_t>(0x2764) << std::endl;
于 2013-08-28T13:19:08.510 回答