c++ linux下输出中文

同样,使用的是VS FOR LINUX进行测试。

converting to execution character set: Invalid or incomplete multibyte or wide character

如果编译时候遇到该错误,则可以加上-finput-charset  -fexecute-charset  g++编译选项解决。因为linux下gcc希望源文件是UTF-8格式,所以都改成UTF-8就好了。同时,也可以vs下装个forceUTF8插件。

搜了下,网上有说使用wprintf的,比如:

wchar_t c= L'中国';
wprintf(L"%c",c);

wprintf(L"%ls\n", L"中华人民共和国");

测试的时候发现wprintf没有打印任何东西。

有说使用locale loc("chs");的

locale loc("chs");

wcout.imbue( loc );

也有说setlocale( LC_CTYPE,"chs");的

使用chs编码,运行时就报异常了,难道都没测过么???

最后还是自己逐个调试解决了。如下:

setlocale(LC_ALL, "zh_CN.UTF-8");

wchar_t zh_cn = L'';
wchar_t zh_cns[] = L"中国";

wchar_t another_w[sizeof(zh_cns)/sizeof(wchar_t)] = {0};
wcscpy(another_w, zh_cns);

printf("%ls。。。....%ls。。。%lc\n", zh_cns, another_w,zh_cn);

加上-finput-charset  -fexecute-charset  g++编译选项或者在VS中把文件设置为UTF-8带签名格式即可。

输出:

中国。。。....中国。。。国

最后,宽字符的操作函数和char不同,常用的可以参考http://www.cnblogs.com/lidabo/p/6912788.html。

参考:

https://blog.csdn.net/wangsen_sc/article/details/6915995

https://blog.csdn.net/weiwangchao_/article/details/43453053

https://blog.csdn.net/angelxf/article/details/7803495

http://www.cplusplus.com/reference/cstdio/printf/(关键时候看官方手册)

猜你喜欢

转载自www.cnblogs.com/zhjh256/p/9288596.html