要表示角色,您可以使用通用角色名称 (UCN)。字符“ф”的 Unicode 值是 U+0444,因此在 C++ 中您可以将其写为“\u0444”或“\U00000444”。此外,如果源代码编码支持该字符,那么您可以在源代码中按字面意思编写它。
// both of these assume that the character can be represented with
// a single char in the execution encoding
char b = '\u0444';
char a = 'ф'; // this line additionally assumes that the source character encoding supports this character
打印这些字符取决于您要打印的内容。如果您要打印到 Unix 终端模拟器,终端模拟器正在使用支持此字符的编码,并且该编码与编译器的执行编码相匹配,那么您可以执行以下操作:
#include <iostream>
int main() {
std::cout << "Hello, ф or \u0444!\n";
}
这个节目does not要求 'ф' 可以用单个字符表示。在 OS X 和大多数现代 Linux 安装上,这都可以正常工作,因为源、执行和控制台编码都将是 UTF-8(支持所有 Unicode 字符)。
Windows 的情况就更困难了,并且有不同的可能性和不同的权衡。
如果您不需要可移植代码(您将使用 wchar_t,这在其他平台上确实应该避免),可能最好的方法是将输出文件句柄的模式设置为仅采用 UTF-16 数据。
#include <iostream>
#include <io.h>
#include <fcntl.h>
int main() {
_setmode(_fileno(stdout), _O_U16TEXT);
std::wcout << L"Hello, \u0444!\n";
}
可移植代码更加困难。