如何在 C 中从数组打印无符号字符?

问题描述 投票:0回答:1

尝试打印 C 中的字符 ▒。

我最初想将该字符与其他标准 ASCII 字符(例如字母,因此值小于 127)一起包含在

char
数组中。

我发现这个字符的 ASCII 十进制值为 178,所以我想我需要将数组类型更改为

unsigned char
以包含从 0 到 255 的值。

以下代码尝试在控制台中打印该字符:

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

int main(void) {

    printf("Raw unicode call: \u2592\n");

    unsigned char array[2][3] = {
        { 35, 0x26, 0x27 },
        { 0x28, 0x29, 0x2A }
    };

    array[1][2] = 178;

    for (int i=0; i<2; i++) {
        for (int j=0; j<3; j++) {
            printf("Array[%d][%d]: %c\n", i, j, array[i][j]);
        }
    }
}

代码使用

\u2592
调用成功打印了我想要的字符,但这不是我想要的。我必须循环遍历数组并显示每个字符。循环时,输出可以清晰显示< 127 ASCII values, but when asked to display the character 178, nothing shows on screen. Here is the output:

Raw unicode call: ▒
Array[0][0]: #
Array[0][1]: &
Array[0][2]: '
Array[1][0]: (
Array[1][1]: )
Array[1][2]:  

请帮忙!谢谢

arrays c linux gcc char
1个回答
0
投票

该字符在 UTF-8 中是三个字节:

0xe2, 0x96, 0x92
。 (不是 178。)如果要“循环”打印 UTF-8 字符,每个字符可能是 1、2、3 或 4 个字节,则需要确定每个字符的字节数,然后打印这些字节在一起。

© www.soinside.com 2019 - 2024. All rights reserved.