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

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

 

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

 1 #include<stdio.h>
 2 #include<wchar.h> //putwchar wprintf wchar_t 
 3 #include<locale.h> //setlocale
 4 
 5 int main(void)
 6 {
 7     //让wprintf可以输出中文s
 8     setlocale(LC_ALL, "zh_CN.UTF-8");       //注意这里的zh_CN.UTF-8不能写成chs
 9 
10     wprintf(L"--%c--%lc--\n", L'a', L'');
11     putwchar(L'');
12     putwchar(L'\n');
13 
14     wchar_t a = L'';
15     char  b = 'b';
16     wchar_t *c = L"我是中国好少年";
17     char *d = "我是中国好少年";
18     char *e = "e我是中国好少年";
19     wprintf(L"--%lc--%c--\n", a, b);
20  
21     wprintf(L"--%ls--%s--%s--\n", c,d,e);
22 }

 

 

 

结果如下

注意:

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

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

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

posted @ 2020-04-16 12:17  mindulmindul  阅读(2577)  评论(0编辑  收藏  举报