gpt4 book ai didi

c - 在 C 中打印一个 unicode 框

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:04 25 4
gpt4 key购买 nike

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

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

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

#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?

而且似乎我仍然需要设置语言环境(即使是 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;
}

我显然遗漏了一些东西,但不能完全弄清楚它是什么。

最佳答案

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

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

#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 支持和其他一些好处,我建议使用 iTerm2在 MacOS 上。

关于c - 在 C 中打印一个 unicode 框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34937375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com