嗨,我试图将 unicode 字符串输出到带有 iostreams 的控制台,但失败了。
我发现了这个: 在 c++ 控制台应用程序中使用 unicode 字体,这个片段有效。
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 的方法。有什么建议么?
这不起作用:
SetConsoleOutputCP(CP_UTF8);
utf8_locale = locale(old_locale,new boost::program_options::detail::utf8_codecvt_facet());
wcout.imbue(utf8_locale);
wcout << L"¡Hola!" << endl;
编辑 除了将此片段包装在流中之外,我找不到任何其他解决方案。希望,有人有更好的想法。
//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;
}
原文由 Andrew 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 Win10 上使用带有 UNICODE 控制台应用程序的 VS2019 进行测试,发现以下测试西班牙语和日语:
如果你只是
wprintf
一个字符串,那么你会得到错误的西班牙语字符(日语未经测试,但肯定它不会工作)。看起来默认的“C”语言环境默认是 ASCII(PC 的传统扩展 ASCII 整理表)。使用:
setlocale(LC_ALL, "");
在使用 西班牙语(墨西哥) Windows 语言设置并且输出良好(lucida 控制台字体)时,将正确的代码页设置为 CP1252。但是,日语输出(使用 日语 Windows 语言)被抑制(意味着这些字符不输出,输出普通拉丁字符)。使用:’_setmode(_fileno(stdout), _O_U16TEXT);` 输出对所有人都有效。但是,所有输出都是 16 位,因此重定向到文件输出 16 位字符。
using:
printf
andUTF-8
text output withSetConsoleOutputCP(CP_UTF8)
also works (but not if you set it aftersetlocale(LC_ALL, "");
- I had to remove that使输出工作)。字体:对于亚洲字符,使用 MS Mincho,对于其他字符,您可以使用 Lucida Console。