首页 > 解决方案 > 如何输出/输入多字节符号?

问题描述

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

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 中得到一个宽字符吗?

标签: c++unicodeutf-16stdstring

解决方案


这在我的机器上有效。我的源代码文件是 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();
}

推荐阅读