C语言 打印wchar到Linux控制台



我的C程序粘贴在下面。在bash中,程序打印"char is",Ω不打印。我的语言环境都是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 %cn", myChar1);
}

这很有趣。显然,编译器将omega从UTF-8翻译为UNICODE,但不知怎么的,libc把它弄乱了。

首先:%c -格式说明符期望char(即使在wprintf版本中),因此您必须指定%lc(因此对于字符串指定%ls)。

其次,如果您像这样运行代码,区域设置设置为C(它不会自动从环境中获取)。您必须使用一个空字符串调用setlocale来从环境中获取区域设置,这样libc就可以正常运行了。

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

对于建议修复LIBC的答案,您可以这样做:

#include <stdio.h>
#include <wchar.h>
#include <stdlib.h>
// NOTE: *NOT* thread safe, not re-entrant
const char* unicode_to_utf8(wchar_t c)
{
    static unsigned char b_static[5];
    unsigned char* b = b_static; 
    if (c<(1<<7))// 7 bit Unicode encoded as plain ascii
    {
        *b++ = (unsigned char)(c);
    }
    else if (c<(1<<11))// 11 bit Unicode encoded in 2 UTF-8 bytes
    {
        *b++ = (unsigned char)((c>>6)|0xC0);
        *b++ = (unsigned char)((c&0x3F)|0x80);
    }
    else if (c<(1<<16))// 16 bit Unicode encoded in 3 UTF-8 bytes
        {
        *b++ = (unsigned char)(((c>>12))|0xE0);
        *b++ =  (unsigned char)(((c>>6)&0x3F)|0x80);
        *b++ =  (unsigned char)((c&0x3F)|0x80);
    }
    else if (c<(1<<21))// 21 bit Unicode encoded in 4 UTF-8 bytes
    {
        *b++ = (unsigned char)(((c>>18))|0xF0);
        *b++ = (unsigned char)(((c>>12)&0x3F)|0x80);
        *b++ = (unsigned char)(((c>>6)&0x3F)|0x80);
        *b++ = (unsigned char)((c&0x3F)|0x80);
    }
    *b = '';
    return b_static;
}

int main() {
    int r;
    wchar_t myChar1 = L'Ω';
    r = printf("char is %sn", unicode_to_utf8(myChar1));
    return 0;
}

在输出前使用{glib,libiconv,ICU}将其转换为UTF-8

最新更新