gpt4 book ai didi

c++ - 在 Windows 控制台应用程序中输出 unicode 字符串

转载 作者:太空宇宙 更新时间:2023-11-04 12:52:33 25 4
gpt4 key购买 nike

您好,我尝试使用 iostreams 将 unicode 字符串输出到控制台,但失败了。

我找到了这个:Using unicode font in c++ console app这个片段有效。

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;
}

最佳答案

我在这里使用 Visual Studio 2010 验证了一个解决方案。通过这个 MSDN articleMSDN blog post .技巧是对 _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;
}

截图:

Unicode in console

关于c++ - 在 Windows 控制台应用程序中输出 unicode 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48309070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com