一次搞清楚c++程序的字符编码问题

文章详细描述了在WindowsVisualStudio2019环境下,不同编译选项(如/utf-8)和文件编码对cpp文件中字符串处理的影响,以及exe中字符串的编码问题,强调了UTF-8编码对于跨平台支持的重要性。
摘要由CSDN通过智能技术生成

下面在 windows visual studio 2019上验证,工程如下:

叫法说明:

加编译选项 /utf-8指的是 

文件编码指的是cpp文件的编码格式

运行时编码        

exe中字符串编码

字符 ‘我’在不同的编码中的对应数字 

我, utf8, E6 88 91
我, ANSI, CE D2
我, utf16BE, 62 11  
我, utf16LE, 11 62 

结果如下列表

=========================================================================

加编译选项 /utf-8
文件编码u8bom                                        运行时编码        exe中字符串编码
std::string str1("/我std::string");            utf8                  utf8
std::string str2(u8"u8/我std::string");    utf8                  utf8
std::wstring str3(L"L/我std::string");     unicode           unicode           

加编译选项 /utf-8
文件编码u8                                                运行时编码        exe中字符串编码
std::string str1("/我std::string");           utf8             utf8
std::string str2(u8"u8/我std::string");    utf8             utf8
std::wstring str3(L"L/我std::string");     unicode       unicode

加编译选项 /utf-8
文件编码ANSI                                          运行时编码        exe中字符串编码
std::string str1("/我std::string");            ANSI             ANSI
std::string str2(u8"u8/我std::string");    ANSI             ANSI
std::wstring str3(L"L/我std::string");     乱码(/我std对应 2F 00 0E 00 73 00 74 00 64 00)           乱码(/我std对应 2F 00 0E 00 73 00 74 00 64 00)


=========================================================================

不加编译选项 /utf-8
文件编码u8bom                                   运行时编码        exe中字符串编码
std::string str1("/我std::string");           ANSI             ANSI
std::string str2(u8"u8/我std::string");    utf8              utf8
std::wstring str3(L"L/我std::string");     unicode        unicode

不加编译选项 /utf-8
文件编码u8                                           运行时编码        exe中字符串编码
std::string str1("/我std::string");           utf8                  utf8
std::string str2(u8"u8/我std::string");    乱码(/我std对应 2F E9 8E B4 E6 86 87 74 64)             乱码(/我std对应 2F E9 8E B4 E6 86 87 74 64)
std::wstring str3(L"L/我std::string");     乱码(/我std对应 2F 00 B4 93 87 61 74 00 64 00)          乱码(/我std对应 2F 00 B4 93 87 61 74 00 64 00)

不加编译选项 /utf-8
文件编码ANSI                                运行时编码               exe中字符串编码
std::string str1("/我std::string");        ANSI                     ANSI
std::string str2(u8"u8/我std::string");    utf8                  utf8
std::wstring str3(L"L/我std::string");     unicode            unicode

总结

考虑到跨平台编码 winsdows mac linux,似乎 文件编码保存成utf8 编译选项也指定成utf8,能比较的支持跨平台

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值