本文介绍了使用 Visual Studio 在控制台中输出 utf8(宽流)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我在 Windows 10 上用 mingw32 编译这段代码,它就可以工作.并发出正确的结果,如下所示:
C:\prj\cd>bin\main.exe1°à€3§4ç5@の,は,でした,象形字;
确实,当我尝试使用 Visual Studio 17 编译它时,相同的代码会发出错误的字符
/out:prova.exe证明文件C:\prj\cd>prova.exe1°Ã â€3§4ç5@ã®,ã¯,ã§ã—ãŸ,象形å—;C:\prj\cd>
这里的源代码:
#include #include #include #include #include #include int main ( void ){_wsetlocale(LC_ALL, L"it_IT.UTF-8");//设置区域设置宽字符串_setmode(_fileno(stdout),_O_U8TEXT);//设置控制台的语言环境SetConsoleCP(CP_UTF8);SetConsoleOutputCP(CP_UTF8);//启用缓冲以防止 VS 切碎 UTF-8 字节序列setvbuf(标准输出,nullptr,_IOFBF,1000);std::wstring test = L"1°à€3§4ç5@の,は,でした,象形字;";std::wcout <<测试<
我已经阅读了几个主题:
然后显示所有字符:
This piece of code works if i compiled it with mingw32 on windows 10.and emits right result, as you can see below :
C:\prj\cd>bin\main.exe
1°à€3§4ç5@の,は,でした,象形字 ;
Indeed when i try to compile it with Visual Studio 17, same code emits wrong chracters
/out:prova.exe
prova.obj
C:\prj\cd>prova.exe
1°à €3§4ç5@ã®,ã¯,ã§ã—ãŸ,è±¡å½¢å— ;
C:\prj\cd>
here source code :
#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;
}
I have read several topics :
How to print UTF-8 strings to std::cout on Windows?
How to make std::wofstream write UTF-8?
and many others, but somehtins goes wrong ...can you help me ?
解决方案
The following works for me:
#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;
}
But I had to change the font to
SimSun-ExtB
:
Then all the characters are shown:
这篇关于使用 Visual Studio 在控制台中输出 utf8(宽流)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!