如何在C/C++中输出Unicode字符

6

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

使用C或C ++在Windows控制台中输出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;
}

感谢您的提前帮助。 :)
1个回答

11

大多数字符需要超过一个字节才能编码,但是std::cout当前使用的locale只会输出ASCII字符。因此,在输出流中可能会看到很多奇怪的符号或问号。您应该使用使用UTF-8的locale来imbue std::wcout,因为这些字符不受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名称无效” - user2581142
@user2581142 你在哪个操作系统上运行这个程序(Linux、Windows等)? - David G
我正在我的Linux Mint 14上使用虚拟Windows XP。 - user2581142
@user2581142 Windows不像其他操作系统一样解释Unicode。您需要使用不同的方法,我将在我的更新中展示。 - David G
谢谢,它终于可以工作了。我需要将控制台字体更改为“Lucida Console”,它在Microsoft Visual Studio 2010中作为Win32控制台应用程序运行。但是,在Code Blocks 12.11中无法正常工作。 - user2581142
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接