C ++ Unicode字符打印 [英] C++ unicode characters printing

查看:103
本文介绍了C ++ Unicode字符打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 iostream 在Linux终端上打印一些Unicode字符。奇怪的事情发生了。当我写时:

I need to print some unicode characters on the Linux terminal using iostream. Strange things happen though. When I write:

cout << "\u2780";

我得到:,几乎正是我想要的但是,如果我这样写:

I get: , which is almost exactly what I want. However if I write:

cout << '\u2780';

我得到: 14851712

问题是,我不知道在编译时要打印的确切字符。因此,我想执行以下操作:

The problem is, I don't know the exact character to be printed at compile-time. Therefore I'd like to do something like:

int x;
// some calculations...
cout << (char)('\u2780' + x);

哪些印刷品:。使用 wcout wchar_t 也不起作用。如何获得正确的打印?

Which prints: . Using wcout or wchar_t instead don't work either. How do I get correct printing?

从网上发现的情况来看,直接使用Debian Wheezy仓库中的g ++ 4.7.2编译器似乎很重要。

From what I found around on the Internet it seems important that I use g++ 4.7.2 compiler straight from Debian Wheezy repository.

推荐答案

Unicode字符 \u2780 不在<$的范围内c $ c> char 数据类型。您应该已经收到此编译器警告,告诉您有关它的信息:(至少我的g ++ 4.7.3给出了此提示)

The Unicode character \u2780 is outside of the range for the char datatype. You should have received this compiler warning to tell you about it: (at least my g++ 4.7.3 gives it)

test.cpp:6:13: warning: multi-character character constant [-Wmultichar]

如果要像U + 2780这样的字符作为单个单位使用,您将必须使用widechar数据类型 wchar_t ,或者如果您很幸运能够使用C ++ 11 , char32_t char16_t 。请注意,一个16位单元不足以表示Unicode字符的全部范围。

If you want to work with characters like U+2780 as single units you'll have to use the widechar datatype wchar_t, or if you are lucky enough to be able to work with C++11, char32_t or char16_t. Note that one 16-bit unit is not enough to represent the full range of Unicode characters.

如果这对您不起作用,可能是因为默认的 C语言环境不支持非ASCII输出。要解决该问题,您可以在程序开始时调用 setlocale 。这样,您可以输出用户语言环境支持的所有字符:(可能支持或不支持您使用的所有字符)

If that's not working for you, it's probably because the default "C" locale doesn't have support for non-ASCII output. To fix that problem you can call setlocale in the start of the program; that way you can output the full range of characters supported by the user's locale: (which may or may not have support for all of the characters you use)

#include <clocale>
#include <iostream>

using namespace std;

int main() {
    setlocale(LC_ALL, "");
    wcout << L'\u2780';
    return 0;
}

这篇关于C ++ Unicode字符打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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