为什么这个C程序输出出现乱码?

发布于 2025-01-17 07:14:10 字数 417 浏览 3 评论 0原文

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

int main() {
//    setlocale("LC_ALL","");
    unsigned char utf[]={0xe4,0xb8,0x80,0x0a};
    printf("%s",utf);
    return 0;
}

  • 输出的前四个字节是正确的。控制台中的第二行不是预期的

在此处输入图像描述

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

int main() {
//    setlocale("LC_ALL","");
    unsigned char utf[]={0xe4,0xb8,0x80,0x0a};
    printf("%s",utf);
    return 0;
}

  • The first four bytes of output are correct. The second line in the console is not expected

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雄赳赳气昂昂 2025-01-24 07:14:10

您的数组缺少所需的空终止符字符串,因此 printf 继续打印超出数组末尾的字节,直到遇到空字节为止。 (或者当您的程序由于越界访问而崩溃时。)

添加空字节:

unsigned char utf[]={0xe4,0xb8,0x80,0x0a,0x00};

Your array is missing the null terminator strings require, so printf keeps on printing bytes beyond the end of the array until it happens upon a null byte. (Or when your program crashes due to an out of bounds access.)

Add the null byte:

unsigned char utf[]={0xe4,0xb8,0x80,0x0a,0x00};
玉环 2025-01-24 07:14:10

%s 格式需要一个指向字符串的指针作为相应的参数。即输出字符序列应以终止零字符'\0' 结束。

该数组

unsigned char utf[]={0xe4,0xb8,0x80,0x0a};

不包含字符串。因此,您需要明确指定要输出的字符数。例如

printf("%.*s", 4, utf);

The format %s expects a pointer to a string as the corresponding argument. That is the sequence of outputted characters shall be ended with the terminating zero character '\0'.

This array

unsigned char utf[]={0xe4,0xb8,0x80,0x0a};

does not contain a string. So you need to specify explicitly how many characters you are going to output. For example

printf("%.*s", 4, utf);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文