如何将std :: string写入UTF-8文本文件 [英] How to write a std::string to a UTF-8 text file

查看:382
本文介绍了如何将std :: string写入UTF-8文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在C ++中向文本文件中写一些简单的行,但是我希望它们以UTF-8编码.最简单的方法是什么?

解决方案

UTF-8影响std::string的唯一方法是size()length(),并且所有索引均以字节而不是字符为单位./p>

而且,如sbi所指出的那样,增加std::string提供的迭代器将按字节而不是按字符前进,因此它实际上可以指向多字节UTF-8代码点的中间.标准库中没有提供支持UTF-8的迭代器,但是'Net上有一些迭代器.

如果您还记得这一点,则可以将UTF-8放入std::string,将其写入文件等,所有操作都通过通常的方式进行(我的意思是您使用不带UTF-的std::string的方式-内部8个).

您可能希望以字节顺序标记开始文件,以便其他程序知道它是UTF-8.

I just want to write some few simple lines to a text file in C++, but I want them to be encoded in UTF-8. What is the easiest and simple way to do so?

解决方案

The only way UTF-8 affects std::string is that size(), length(), and all the indices are measured in bytes, not characters.

And, as sbi points out, incrementing the iterator provided by std::string will step forward by byte, not by character, so it can actually point into the middle of a multibyte UTF-8 codepoint. There's no UTF-8-aware iterator provided in the standard library, but there are a few available on the 'Net.

If you remember that, you can put UTF-8 into std::string, write it to a file, etc. all in the usual way (by which I mean the way you'd use a std::string without UTF-8 inside).

You may want to start your file with a byte order mark so that other programs will know it is UTF-8.

这篇关于如何将std :: string写入UTF-8文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆