为什么这个C程序输出出现乱码?
#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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的数组缺少所需的空终止符字符串,因此 printf 继续打印超出数组末尾的字节,直到遇到空字节为止。 (或者当您的程序由于越界访问而崩溃时。)
添加空字节:
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:
%s
格式需要一个指向字符串的指针作为相应的参数。即输出字符序列应以终止零字符'\0'
结束。该数组
不包含字符串。因此,您需要明确指定要输出的字符数。例如
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
does not contain a string. So you need to specify explicitly how many characters you are going to output. For example