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/2492077/

相关文章:

c++ - 复杂的std::map、结构、std::deque问题

java - 为什么 System.out/err 在 Java 中实现为字节流?

c++ - 每 n 次迭代将输出写入文件

php - 为什么 PHP DOMDocument loadHTML 对波斯字符不起作用?

c++ - QML/C++ 问题中的 Unicode

unicode - UTF-8 二进制文件必须在 Erlang 的二进制文字中包含/utf8 吗?

c++ fstream 在 1 个函数之后不起作用(通过引用)

C++ 新手 : my loop should CHANGE a string, 然后将字符串打印到文件中。但它正在添加到字符串中

c++ - 关于 Struct 上的 new 和 delete 运算符

c++ - C++中位运算符的定义是什么?