在 Windows 控制台应用程序中输出 unicode 字符串 [英] Output unicode strings in Windows console app
问题描述
我试图用 iostreams 将 unicode 字符串输出到控制台,但失败了.
Hi I was trying to output unicode string to a console with iostreams and failed.
我发现了这个:在 C++ 控制台应用程序中使用 unicode 字体并且此代码段有效.
I found this: Using unicode font in c++ console app and this snippet works.
SetConsoleOutputCP(CP_UTF8);
wchar_t s[] = L"èéøÞǽлљΣæča";
int bufferSize = WideCharToMultiByte(CP_UTF8, 0, s, -1, NULL, 0, NULL, NULL);
char* m = new char[bufferSize];
WideCharToMultiByte(CP_UTF8, 0, s, -1, m, bufferSize, NULL, NULL);
wprintf(L"%S", m);
但是,我没有找到任何使用 iostreams 正确输出 unicode 的方法.有什么建议吗?
However, I did not find any way to output unicode correctly with iostreams. Any suggestions?
这不起作用:
SetConsoleOutputCP(CP_UTF8);
utf8_locale = locale(old_locale,new boost::program_options::detail::utf8_codecvt_facet());
wcout.imbue(utf8_locale);
wcout << L"¡Hola!" << endl;
编辑我找不到任何其他解决方案,只能将此代码段包装在流中.希望有人有更好的想法.
EDIT I could not find any other solution than to wrap this snippet around in a stream. Hope, somebody has better ideas.
//Unicode output for a Windows console
ostream &operator-(ostream &stream, const wchar_t *s)
{
int bufSize = WideCharToMultiByte(CP_UTF8, 0, s, -1, NULL, 0, NULL, NULL);
char *buf = new char[bufSize];
WideCharToMultiByte(CP_UTF8, 0, s, -1, buf, bufSize, NULL, NULL);
wprintf(L"%S", buf);
delete[] buf;
return stream;
}
ostream &operator-(ostream &stream, const wstring &s)
{
stream - s.c_str();
return stream;
}
推荐答案
我在这里使用 Visual Studio 2010 验证了一个解决方案.通过这个 MSDN 文章 和 MSDN 博客文章.诀窍是对 _setmode(..., _O_U16TEXT)
的模糊调用.
I have verified a solution here using Visual Studio 2010. Via this MSDN article and MSDN blog post. The trick is an obscure call to _setmode(..., _O_U16TEXT)
.
解决方案:
#include <iostream>
#include <io.h>
#include <fcntl.h>
int wmain(int argc, wchar_t* argv[])
{
_setmode(_fileno(stdout), _O_U16TEXT);
std::wcout << L"Testing unicode -- English -- Ελληνικά -- Español." << std::endl;
}
截图:
这篇关于在 Windows 控制台应用程序中输出 unicode 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!