c++ linux下输出中文

时间:2023-03-10 01:44:39
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)] = {};
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。

上述设置后,环境中就是指定的字符集了,但是vs监视窗口仍然会是显示16进制,如下:

c++ linux下输出中文

经查帖子https://blog.****.net/lainegates/article/details/72236321,将C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Packages\Debugger\Visualizers\stl.natvis的将文件583-586行改为如下:

      <DisplayString Condition="_Mypair._Myval2._Myres &lt; _Mypair._Myval2._BUF_SIZE">{_Mypair._Myval2._Bx._Buf,s8}</DisplayString>
<DisplayString Condition="_Mypair._Myval2._Myres &gt;= _Mypair._Myval2._BUF_SIZE">{_Mypair._Myval2._Bx._Ptr,s8}</DisplayString>
<StringView Condition="_Mypair._Myval2._Myres &lt; _Mypair._Myval2._BUF_SIZE">_Mypair._Myval2._Bx._Buf,s8</StringView>
<StringView Condition="_Mypair._Myval2._Myres &gt;= _Mypair._Myval2._BUF_SIZE">_Mypair._Myval2._Bx._Ptr,s8</StringView>

之后,vs2015即可在debug时正常显示utf-8字符。TODO


还有个帖子说,“只需要将要显示的字符串拉到Watch中,并在变量后面添加,s8即可显示”,经测,这么做是不行的,监视窗口会报错,如下:

c++ linux下输出中文

参考:

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

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

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

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