2016-01-22 60 views
0

我想打印在C這個中等色調統一盒unicode的盒子:▒打印用C

(我做的練習以K & R和結果得到的是牽制在一個有關使直方圖...)。我知道我的unix術語(Mac OSX)可以顯示該框,因爲我用該框保存了一個文本文件,並使用cat textfilewithblock並打印該塊。

到目前爲止,我最初嘗試:

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

int main(){ 
    wprintf(L"▒\n"); 
    return 0; 
} 

並沒有打印任何

iMac-2$ ./a.out 
iMac-2:clang vik$ 

我做了搜索,發現這一點:unicode hello world for C?

而且好像我還是要設置locale(即使utf8中的執行環境?我仍然試圖找出爲什麼這一步是必要的)但無論如何,它的工作原理! (後有點奮鬥終於實現了正確的字符串爲en_US.UTF-8,而不是,我曾在其他地方見過en_US.utf8 ...)

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

int main(){ 
    setlocale (LC_ALL, "en_US.UTF-8"); 
    wprintf(L"▒\n"); 
    return 0; 
} 

輸出如下:

iMac-2$ ./a.out 
▒ 
iMac-2$ 

但是當我嘗試下面的代碼...放在UTF-8十六進制(我從這裏得到:http://www.utf8-chartable.de/unicode-utf8-table.pl?start=9472&unicodeinhtml=dec)這是盒子的0xe29692,而不是粘貼在盒子本身,它不再工作。

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

int main(){ 
    setlocale (LC_ALL, "en_US.UTF-8"); 
    wchar_t box = 0xe29692; 
    wprintf(L"%lc\n", box); 
    return 0; 
} 

我明顯錯過了一些東西,但無法弄清楚它是什麼。

+0

我應該注意到,我正在使用以下編譯器命令:'cc --std = c11' – RandomUser762

+0

可能會有幫助:http://stackoverflow.com/q/12017342/2476755 – royhowie

+0

在Mac OSX上, t需要'wchar.h','wprintf'或'L'前綴或'setlocale'。如果你想打印一個盒子,只需打印一個盒子:'printf(「▒\ n」);' – user3386109

回答

3

MEDIUM SHADE代碼點的unicode值不是0xe29692,它是0x2592<E2><96><92>是UTF-8中此代碼點的3字節編碼。

您可以打印這個東西使用寬字符的API:只需直接打印UTF-8編碼

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

int main(void) { 
    setlocale(LC_ALL, "en_US.UTF-8"); 
    wchar_t box = 0x2592; 
    wprintf(L"%lc\n", box); // or simply printf("%lc\n", box); 
    return 0; 
} 

或者:

#include <stdio.h> 

int main(void) { 
    printf("\xE2\x96\x92\n"); 
    return 0; 
} 

或者,如果你的文本編輯器編碼的源文件在UTF-8中:

#include <stdio.h> 

int main(void) { 
    printf("▒\n"); 
    return 0; 
} 

但是請注意,這不起作用:putchar('▒');

此外,對於完整的Unicode支持和一些更多的好東西,我建議在MacOS上使用iTerm2

+1

Mac'Terminal.app'支持Unicode就好了;您甚至可以選擇通過不同配置文件使用的編碼。 – nneonneo

+0

@nneonneo:是的,但過去不太完整,我使用'iTerm2'的原因不同:它允許更多控制重新映射修改鍵,我使用了很多,尤其是在本地編輯和使用我自己的遠程編輯時版本的emacs';-)' – chqrlie

+0

Ohhhhh我明白了!謝謝! utf-8「encoding」是一個最多4個字節的字符串,而不是一個1到4個字節的值。 – RandomUser762

1

框字符是U + 2592,它轉換爲UTF-8中的0xE2 0x96 0x92。你的第三個節目的這種調整主要是爲我工作:

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

int main(void) 
{ 
    setlocale (LC_ALL, "en_US.UTF-8"); 
    wchar_t box = 0xe29692; 
    wprintf(L"%lc\n", box); 
    wprintf(L"\n\nX\n\n"); 
    box = L'\u2592'; //0xE2 0x96 0x92 = U+2592 
    wprintf(L"%lc\n", box); 
    wprintf(L"\n\n0x%.8X\n\n", box); 
    box = 0x2592; 
    wprintf(L"%lc\n", box); 
    return 0; 
} 

我得到的輸出是:

X 

▒ 


0x00002592 

▒ 

第一打印操作產生什麼用的;其他人工作。

在Mac OS X 10.10.5上測試。我碰巧編譯了GCC 5.3.0(我編譯),但是我得到了與XCode 7.0.2和clang相同的輸出。