繁体   English   中英

将 Unicode 输出到控制台的最佳方法是什么?

[英]What is the best way to output Unicode to console?

我正在 Visual Studio 2019 中使用 C++17。我已经阅读了一些关于编码的内容,但我对它们仍然不太满意。 我想将 UNICODE 字符输出到屏幕。 为此,我使用以下代码

#include <iostream>
#include <fcntl.h>
#include <io.h>

std::wstring symbol{ L"♚" };

_setmode(_fileno(stdout), _O_WTEXT);
std::wcout << symbol; //This works fine
std::cout << "Hello"; //This gives "Debug Assertion Failed! Expression: buffer_size % 2 == 0"
_setmode(_fileno(stdout), O_TEXT); //Need this to make std::cout work normally
std::cout << "World"; //This works fine

所以我可以在每次需要输出 std::wstring 时将 setmode 设置为 _O_WTEXT,然后返回到 O_TEXT。 但是,我担心这可能是一种低效的做事方式。 有没有更好的方法来做到这一点? 我已经阅读了 C++ 中称为本机宽字符支持的内容,但我发现它很难理解。 有人能照亮我吗?

编辑

为了补充上述内容,使用_setmode(_fileno(stdout),_O_U16TEXT)在尝试使用std::cout而不将模式设置回时会导致与上述相同的行为。 如果我使用_setmode(_fileno(stdout),_O_U8TEXT)代替,我的代码无法编译,并给出错误的'symbol': redefinition, different basic types'<<': illegal for class使用时std::coutstd::string symbol = <insert any of the possibilities I tried in the snippet below>

有人建议我使用 UTF-8 std::string以便能够使用std::cout ,这样就可以避免切换到宽模式。 谁能帮我看看如何实现这一目标? 我试过了

std::string symbol = "\u265A"; //using std::cout gives "?" and triggers warning *
std::string symbol = "♚"; //Same as above

std::string symbol = u8"\u265A"; //using std::cout gives "ÔÖÜ"
std::string symbol = u8"♚"; //Same as above

* Severity Code Description Project File Line Suppression State Warning C4566 character represented by universal-character-name '\♚' cannot be represented in the current code page (1252)

我已经读过使用来自标题<Windows.h> WideCharToMultiByte() 从std::wstring转换为 UTF-8 std::string是可能的。 那行得通吗? 任何人都可以提供任何帮助吗?

线索在错误消息中。 “...无法在当前代码页 (1252) 中表示”。 所以需要修改代码页。 UTF-8 的代码页标识符是 65001。要更改代码页,请使用SetConsoleOutputCP

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM