用 printf 打印出一个 unicode 字符 [英] printing out a unicode character with printf

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

问题描述

我试图通过将其相应的十进制值传入 printf 来打印出 Ș.输出什么都没有.为什么我的代码不起作用?

I am trying to print out a Ș by passing in its corresponding decimal value into printf. The output is nothing at all. Why doesn't my code work?

#include <stdio.h>
int main()
{
    printf("%lc",536);
    return 0;
}

推荐答案

在 macOS Sierra 10.12.2 和 GCC 6.3.0 上,如果我运行这个程序(从 mb37.c 编译成 mb37):

On macOS Sierra 10.12.2 with GCC 6.3.0, if I run this program (compiled from mb37.c into mb37):

#include <locale.h>
#include <stdio.h>
#include <wchar.h>      /* wint_t */

int main(void)
{
    setlocale(LC_ALL, "");
    printf("%lc\n", (wint_t)536);
    return 0;
}

输出为:

$ ./mb37
Ș
$

我相信,这就是所需的输出.如果删除 setlocale() 行,则根本不会产生任何输出 — 甚至不会产生换行符.使用的语言环境是en_US.UTF-8;我的终端也处理 UTF-8.语言环境名称是通过捕获并打印 setlocale() 的返回值来找到的 - 一个常规字符串.

That, I believe, is the desired output. If the setlocale() line is removed, then no output at all is produced — not even a newline. The locale used is en_US.UTF-8; my terminal handles UTF-8 too. The locale name is found by capturing and printing the return value from setlocale() — a regular string.

wint_t 转换是半可选的;碰巧的是,没有强制转换或 <wchar.h> 标头的 64 位编译也会产生相同的输出,但是 wint_t 是一个轻微的巧合与 int 相同.这需要一些跟踪;wint_t 定义为 __darwin_wint_t 定义为 __darwin_ct_rune_t 定义为 int.为了便于移植,演员阵容是必要的.在某些系统上,可能没有必要(macOS Sierra 就是这样一种系统).

The wint_t cast is semi-optional; it so happens that a 64-bit compilation without the cast or the <wchar.h> header also produces the same output, but there is a mild coincidence that wint_t is the same as int. That takes some tracking; wint_t is defined as __darwin_wint_t which is defined as __darwin_ct_rune_t which is defined as int. To be portably correct, the cast is necessary. On some systems, it may not be necessary (and macOS Sierra is one such system).

printf() 中的换行符不是 100% 必须的,但如果它被省略,下一个提示会紧跟在 U+0218 LATIN CAPITAL LETTER S WITH COMMA BELOW 之后.最好确保输出以换行符结尾.

The newline in the printf() is not 100% necessary, but if it is omitted, the next prompt immediately follows the U+0218 LATIN CAPITAL LETTER S WITH COMMA BELOW. It is better to ensure that the output ends with a newline.

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

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