我正在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)
,则在'symbol': redefinition, different basic types
上使用'<<': illegal for class
时,我的代码将无法编译并出现错误std::cout
和std::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>
。那行得通吗?有人可以提供任何帮助吗?
答案 0 :(得分:1)
提示在错误消息中。 “ ...无法在当前代码页中表示(1252)”。因此,代码页需要更改。 UTF-8的code page identifier是65001。要更改代码页,请使用SetConsoleOutputCP
。