C 语言

问题:

打印一句中文

#include <stdio.h>

int main()
{
	char str[] = "你好,世界";
	printf("%s
", str);

	return 0;
}

运行结果

接下来打印这句中文中的“好”字

#include <stdio.h>

int main()
{
	char str[] = "你好,世界";
	printf("%c
", str[1]);

	return 0;
}

运行结果

它打印出来的是问号

原因:

char 类型是为 ascii 定义的,每个字符为 1 个字节,而中文占两个字节

解决方案:

使用 Unicode 编码

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

int main()
{
	wchar_t str[] = L"你好,世界";  // 使用 wchar_t 定义 Unicode 编码的字符类型,L 表示每个字符为两个字节

	setlocale(LC_ALL, "Chs");  // 设置语言环境为简体中文

	wprintf(L"%lc
", str[1]);  // 这里要用 L 和 l

	return 0;
}

运行结果

原文地址:https://www.cnblogs.com/sch01ar/p/9739882.html