打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Writing UTF-8 files in C++

Let’s say you need to write an XML file with this content:

How do we write that in C++?

At a first glance, you could be tempted to write it like this:

When you open the file in IE for instance, surprize! It’s not rendered correctly:

So you could be tempted to say “let’s switch to wstring and wofstream”.

And when you run it and open the file again, no change. So, where is the problem? Well, the problem is that neither ofstream nor wofstream write the text in a UTF-8 format. If you want the file to really be in UTF-8 format, you have to encode the output buffer in UTF-8. And to do that we can use WideCharToMultiByte(). This Windows API maps a wide character string to a new character string (which is not necessary from a multibyte character set). The first argument indicates the code page. For UTF-8 we need to specify CP_UTF8.

The following helper functions encode a std::wstring into a UTF-8 stream, wrapped into a std::string.

With that in hand, all you have to do is doing the following changes:

And now when you open the file, you get what you wanted in the first place.

And that is all!

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
从宽字符转换到UTF8的代码
基于jwSMTP的C++发送Email的Demo
CString、LPSTR、std::string、LPCSTR之间的转换
c 中char*\wchar
宽字符和窄字符的转换接口
wchar
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服