C 语言 - Unicode 解决中文问题


问题:

打印一句中文

#include <stdio.h>

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

	return 0;
}

运行结果

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

#include <stdio.h>

int main()
{
	char str[] = "你好,世界";
	printf("%c\n", 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\n", str[1]);  // 这里要用 L 和 l

	return 0;
}

运行结果

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM