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

时间:2018-05-04 16:32:28

标签: c++ windows unicode outputstream mojibake

如果我在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 print UTF-8 strings to std::cout on Windows?

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

和其他许多人一样,但有些问题...... 你能救我吗?

1 个答案:

答案 0 :(得分:1)

以下适用于我:

#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-ExtBenter image description here

然后显示所有字符: enter image description here