使用 Visual Studio 在控制台中输出 utf8(宽流)

output utf8 in console with Visual Studio (wide stream)

如果我在 windows 10 上用 mingw32 编译这段代码,它就可以工作。 并发出正确的结果,如下所示:

C:\prj\cd>bin\main.exe
1°à€3§4ç5@の,は,でした,象形字 ;

确实,当我尝试用 Visual Studio 17 编译它时,相同的代码发出了错误的字符

/out:prova.exe
prova.obj

C:\prj\cd>prova.exe
1°à€3§4ç5@ã®,ã¯,ã§ã—ãŸ,象形字 ;

C:\prj\cd>

此处源代码:

#include <windows.h>
#include <io.h>
#include <fcntl.h>
#include <stdio.h>
#include <string>
#include <iostream>

int main ( void )
{
    _wsetlocale(LC_ALL, L"it_IT.UTF-8" );   // set locale wide string
    _setmode(_fileno(stdout), _O_U8TEXT);   // set Locale for console
    SetConsoleCP( CP_UTF8 ) ;               
    SetConsoleOutputCP(CP_UTF8);

    // Enable buffering to prevent VS from chopping up UTF-8 byte sequences
    setvbuf(stdout, nullptr, _IOFBF, 1000);

    std::wstring test = L"1°à€3§4ç5@の,は,でした,象形字 ;";
    std::wcout << test << std::endl;

}

我已经阅读了几个主题:

How to make std::wofstream write UTF-8?

和许多其他人,但有些地方出了问题...... 你能帮帮我吗?

以下对我有用:

#include <string>
#include <iostream>
#include <Windows.h>

int main(void)
{
    // use utf8 literal
    std::string test = u8"1°à€3§4ç5@の,は,でした,象形字 ;"; 

    // set code page to utf8
    SetConsoleOutputCP(CP_UTF8);                        

    // Enable buffering to prevent VS from chopping up UTF-8 byte sequences
    setvbuf(stdout, nullptr, _IOFBF, 1000);

    // printing std::string to std::cout, not std::wstring to std::wcout
    std::cout << test << std::endl; 
}

但我不得不将字体更改为 SimSun-ExtB

然后显示所有字符: