wchar:c语言中,输出和表示中文

c语言中的printf和putchar都是为ascii码准备的。要想显示中文,必须通过<wchar.h>这个头文件中(和对应的库)提供的函数wprintf和putwchar来实现。

在使用wprintf之前,设置c语言自身的环境,使用setlocale即可。有<locale.h>提供该函数。示例如下

#include<stdio.h>
#include<wchar.h> //putwchar wprintf wchar_t
#include<locale.h> //setlocale

int main(void)
{
//让wprintf可以输出中文
setlocale(LC_ALL, "zh_CN.UTF-8"); //注意这里的zh_CN.UTF-8不能写成chs

wprintf(L"--%c--%lc--\n", L‘a‘, L‘中‘);
putwchar(L‘中‘);
putwchar(L\n);

wchar_t a = L‘中‘;
char b = ‘b‘;
wchar_t *c = L"我是中国好少年";
char *d = "我是中国好少年";
char *e = "e我是中国好少年";
wprintf(L"--%lc--%c--\n", a, b);
 
wprintf(L"--%ls--%s--%s--\n", c,d,e);
}

结果如下

wchar:c语言中,输出和表示中文

注意:

1. wprintf的format字符串,必须使用L标识,表示这是一个宽字符串,才能为wprintf所用。

2. wprintf中,使用%c或%s可以打印正常的ascii字符或ascii字符串,也可以打印宽字符串。但是要打印宽字符和宽字符串,最好还是用%lc或%ls。

3. 用了wprintf,最好别用printf了,我遇到过问题。

相关推荐