如何输出/输入多字节符号



经过大量搜索后,我开始使用奇怪的代码:

ofstream myfile;
string chars =  "абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
myfile.open ("alphabet.txt");
for (int i = 0; i < 66; i+=2) {
myfile << chars[i] <<chars[i+1] << "n";
}
myfile.close();

但是,真的没有办法从std::string中获得一个宽字符吗?

这在我的机器上运行。我的源代码文件是UTF-8。字符串的格式为UTF-16。输出为UTF-16LE。

随着时间的推移,C++在处理Unicode字符串方面有所改进,但仍有很大的改进空间。

#include <fstream>
#include <string>
using std::ofstream;
using std::string;
int main() {
auto chars = u"абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
auto myfile = ofstream("alphabet.txt");
for (char16_t const* p = chars; *p; ++p) {
auto c = *p;
auto cc = reinterpret_cast<char const*>(&c);
myfile.write(cc, sizeof c);
}
myfile.close();
}

最新更新