如果我在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?
和其他许多人一样,但有些问题...... 你能救我吗?
答案 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;
}