如何在 C/C++ 中输出 unicode 字符 [英] How to output unicode characters in C/C++

查看:54
本文介绍了如何在 C/C++ 中输出 unicode 字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have problems with outputing unicode characters in Windows console. I am using Windows XP and Code Blocks 12.11 with mingw32-g++ compiler.

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

What is the proper way to output unicode characters in Windows console with C or C++?

这是我的 C++ 代码:

This is my C++ code:

#include <iostream>
#include <string>

using namespace std;

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

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

    return 0;
}

提前致谢.:)

推荐答案

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

Most of those characters take more than a byte to encode, but std::cout's currently imbued locale will only output ASCII characters. For that reason you're probably seeing a lot of weird symbols or question marks in the output stream. You should imbue std::wcout with a locale that uses UTF-8 since these characters are not supported by 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 系统,您将需要以下代码:

For Windows systems you will need the following code:

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

这篇关于如何在 C/C++ 中输出 unicode 字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆