在 C 中打印一个 unicode 框

Ran*_*762 2 c unicode utf-8

我正在尝试在 C: 中打印这个中等色调的 unicode 框?

(我正在 K&R 中进行练习,然后在关于制作直方图的练习上偏离了方向......)。我知道我的 unix 术语(Mac OSX)可以显示该框,因为我用该框保存了一个文本文件,并使用cat textfilewithblock并打印了该块。

到目前为止,我最初尝试过:

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

int main(){
  wprintf(L"?\n");
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

没有打印

iMac-2$ ./a.out 
iMac-2:clang vik$
Run Code Online (Sandbox Code Playgroud)

我做了一个搜索,发现了这个:unicode hello world for C?

而且似乎我仍然需要设置语言环境(即使执行环境是 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;
}
Run Code Online (Sandbox Code Playgroud)

输出如下:

iMac-2$ ./a.out 
?
iMac-2$
Run Code Online (Sandbox Code Playgroud)

但是当我尝试以下代码时......放入 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;
}
Run Code Online (Sandbox Code Playgroud)

我显然错过了一些东西,但无法弄清楚它是什么。

chq*_*lie 5

MEDIUM SHADE 代码点的 unicode 值不是0xe29692,而是0x2592。<E2><96><92>是 UTF-8 中此代码点的 3 字节编码。

您可以使用宽字符 API 打印此内容:

#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;
}
Run Code Online (Sandbox Code Playgroud)

或者直接打印 UTF-8 编码:

#include <stdio.h>

int main(void) {
    printf("\xE2\x96\x92\n");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您的文本编辑器以 UTF-8 编码源文件:

#include <stdio.h>

int main(void) {
    printf("?\n");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但请注意,这将不起作用: putchar('?');

此外,对于完整的 unicode 支持和更多好东西,我建议iTerm2在 MacOS 上使用。