【问题标题】:How to output unicode characters in C/C++ [duplicate]如何在 C/C++ 中输出 unicode 字符 [重复]
【发布时间】:2013-07-12 13:52:50
【问题描述】:

我在 Windows 控制台中输出 unicode 字符时遇到问题。 我正在使用带有 mingw32-g++ 编译器的 Windows XP 和 Code Blocks 12.11。

在 Windows 控制台中使用 C 或 C++ 输出 unicode 字符的正确方法是什么?

这是我的 C++ 代码:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    cout << "šđč枊ĐČĆŽ" << endl; // doesn't work

    string s = "šđč枊ĐČĆŽ";
    cout << s << endl;            // doesn't work

    return 0;
}

提前致谢。 :)

【问题讨论】:

    标签: c++ c windows unicode console


    【解决方案1】:

    这些字符中的大多数都需要超过一个字节来编码,但是std::cout 当前被灌输的语言环境将只输出 ASCII 字符。出于这个原因,您可能会在输出流中看到很多奇怪的符号或问号。您应该为std::wcout 灌输使用UTF-8 的语言环境,因为ASCII 不支持这些字符:

    // <locale> is required for this code.
    
    std::locale::global(std::locale("en_US.utf8"));
    std::wcout.imbue(std::locale());
    
    std::wstring s = L"šđč枊ĐČĆŽ";
    std::wcout << s;
    

    对于 Windows 系统,您将需要以下代码:

    #include <iostream>
    #include <string>
    #include <fcntl.h>
    #include <io.h>
    
    int main()
    {      
        _setmode(_fileno(stdout), _O_WTEXT);
    
        std::wstring s = L"šđč枊ĐČĆŽ";
        std::wcout << s;
    
        return 0;
    }
    

    【讨论】:

    • 感谢您的回答,但我仍有问题。如果我运行您的代码,我会收到消息“在抛出 'std::runtime_error'what() 的实例后调用终止:locale::facet::_S_create_c_locale name not valid”
    • @user2581142 你在什么操作系统上运行它(Linux、Windows 等)?
    • 我在我的 Linux Mint 14 上使用虚拟 Windows XP。
    • @user2581142 Windows 不像其他操作系统那样解释 Unicode。您需要使用我将在更新中展示的不同方法。
    • 谢谢,它终于可以工作了。我需要将控制台字体更改为“Lucida Console”,它在 Micosoft Visual Studio 2010 中作为 Win32 控制台应用程序工作。它在代码块 12.11 中不起作用。
    猜你喜欢
    • 2017-03-14
    • 2011-03-10
    • 1970-01-01
    • 2016-10-22
    • 2017-01-29
    • 2023-03-17
    • 1970-01-01
    • 2013-05-05
    • 2020-05-08
    相关资源
    最近更新 更多