c++ - 如何输出/输入多字节符号?
问题描述
经过大量搜索后,我开始使用那个奇怪的代码:
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();
}
推荐阅读
- delphi - 如何使用 Delphi 10.3.3 检测 Windows 11
- prestashop-1.7 - LIst 修饰符 Hooks 不适用于其他管理员配置文件
- java - AssertJ SoftAssertions:收集到 AssertionError 后如何执行自定义代码?
- python - 为什么“is”运算符在 python 的类方法中表现不同?
- javascript - 在 24 小时旅馆时钟功能中形成
- django - 创建时出现 django RelatedObjectDoesNotExist 错误
- reactjs - React App 一些 CSS 属性被忽略
- java - 为什么 AlertDialog 在 Activty RecycleView 适配器中不起作用
- html - 将容器居中到页面中间
- csv - AWS 胶水:当 CSV 包含字符串和时间戳/日期值时,爬虫无法识别元数据