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

标签 c++ unicode iostream windows-console

您好,我尝试使用 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/

相关文章:

c++ - 如何声明 __stdcall 函数指针

c++ - 读取zlib/miniz压缩数据时出现DATA_ERROR

java - 为逃生 telnet 编写 unicode 字符

c++ - 从 C++ 输出中删除逗号

c++ - 使用 Eigen::VectorXd 减少 OpenMP

Unicode 字符使用统计

python - 如何处理 mako 中的 unicode?

c++ - 自定义 std::fstream、std::filebuf 的上溢和下溢函数不会为每个字符调用

c++ - 错误消息 "iostream: no such file or directory"

c++ - 定义内联函数的正确方法是什么?