打印wchar到Linux控制台? [英] Print wchar to Linux console?

查看:415
本文介绍了打印wchar到Linux控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的C程式贴在下面。在bash中,程序打印char is,不打印Ω
。我的区域设置都是en_US.utf8。

My C program is pasted below. In bash, the program print "char is ", Ω is not printed. My locale are all en_US.utf8.

#include <stdio.h>
#include <wchar.h>
#include <stdlib.h>

int main() {
   int r;
   wchar_t myChar1 = L'Ω';
   r = wprintf(L"char is %c\n", myChar1);
}


推荐答案

显然,编译器将omega从UTF-8转换为UNICODE,但不知何故,libc会把它弄乱。

This was quite interesting. Apparently the compiler translates the omega from UTF-8 to UNICODE but somehow the libc messes it up.

首先:%c -format说明符需要 char (即使在 wprintf -version),所以你必须指定%lc (因此%ls 字符串)。

First of all: the %c-format specifier expects a char (even in the wprintf-version) so you have to specify %lc (and therefore %ls for strings).

其次,如果你运行你的代码,语言环境设置为 C 环境)。您必须致电 setlocale 空字符串从环境中获取语言环境,所以libc再次很高兴。

Secondly if you run your code like that the locale is set to C (it isn't automatically taken from the environment). You have to call setlocale with an empty string to take the locale from the environment, so the libc is happy again.

#include <stdio.h>
#include <wchar.h>
#include <stdlib.h>
#include <locale.h>

int main() {
    int r;
    wchar_t myChar1 = L'Ω';
    setlocale(LC_CTYPE, "");
    r = wprintf(L"char is %lc (%x)\n", myChar1, myChar1);
}

这篇关于打印wchar到Linux控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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