将 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

所以我可以将 setmode 设置为 _O_WTEXT,然后每次我需要输出 std::wstring 时返回 O_TEXT。但是,我担心这可能是一种低效的做事方式。有更好的方法吗?我读过 C++ 中所谓的本机 widechar 支持,但我发现它很难理解。谁能照亮我?

编辑

除此之外,使用 _setmode(_fileno(stdout),_O_U16TEXT) 会导致与上述相同的行为,当尝试使用 std::cout 而不重新设置模式时。如果我改用 _setmode(_fileno(stdout),_O_U8TEXT),在 std::string symbol = <insert any of the possibilities I tried in the snippet below>.

上使用 std::cout 时,我的代码将无法编译并给出错误 'symbol': redefinition, different basic types'<<': illegal for class

有人建议我使用 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 '\u265A' cannot be represented in the current code page (1252)

我读过可以使用 header <Windows.h> 中的 WideCharToMultiByte() 从 std::wstring 转换为 UTF-8 std::string。那行得通吗?谁能提供帮助?

线索在错误消息中。 “...无法在当前代码页 (1252) 中表示”。所以需要更改代码页。 code page identifier for UTF-8 is 65001. To change the code page, use SetConsoleOutputCP.