gpt4 book ai didi

c++ - 如何在 C++ 中打印 Unicode 字符

转载 作者:行者123 更新时间:2023-11-30 17:42:07 28 4
gpt4 key购买 nike

我正在尝试打印俄语“ф”(U+0444西里尔小写字母EF)字符,其十进制代码1092 。使用C++,如何打印出这个字符?我本以为类似以下内容的东西会起作用,但是......

int main (){
wchar_t f = '1060';
cout << f << endl;
}

最佳答案

要表示角色,您可以使用通用角色名称 (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";
}

此程序要求“ф”可以用单个字符表示。在 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";
}

可移植代码更加困难。

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com