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

问题描述 投票:2回答:1

我正在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 ++中本机Widechar支持的内容,但是我很难理解。谁能照亮我?

编辑

要添加到上面,使用_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 '\u265A' cannot be represented in the current code page (1252)

我已经阅读过,可以使用标头std::wstring中的WideCharToMultiByte()将std::string转换为UTF-8 <Windows.h>。那行得通吗?有人可以提供任何帮助吗?

c++ unicode c++17 visual-studio-2019 wstring
1个回答
1
投票

提示在错误消息中。 “ ...无法在当前代码页中表示(1252)”。因此,代码页需要更改。 UTF-8的code page identifier为65001。要更改代码页,请使用SetConsoleOutputCP

© www.soinside.com 2019 - 2024. All rights reserved.