求一个使用 wofstream 输出中文到文件的例子
C++ std::wofstream 类输出中内容到文件中失败,代码如下:
int main() {
fs::path currentPath = "D:\\XXX\\DDD\\a.txt";
//===================
std::vector<std::wstring> vec;
vec.push_back(L"1中");
vec.push_back(L"2中");
vec.push_back(L"3中");
std::wofstream ofs(currentPath);
auto it = vec.begin();
while (it != vec.end()) {
ofs << *it;
it++;
}
ofs.close();
return 0;
}
基于Monster 组和GPT的调写:
#include <iostream>
#include <fstream>
#include <locale>
#include <codecvt>
#include <vector>
#include <filesystem>
int main() {
std::vector<std::wstring> vec = {L"1中", L"2中", L"3中"};
std::filesystem::path currentPath = "D:\\XXX\\DDD\\a.txt";
std::wofstream ofs(currentPath);
if (ofs.is_open()) {
std::locale utf8_locale(std::locale(), new std::codecvt_utf8<wchar_t>);
ofs.imbue(utf8_locale); // 设置输出流的编码为 UTF-8
for (const auto& s : vec) {
ofs << s << std::endl;
}
ofs.close();
std::cout << "写入完成" << std::endl;
}
else {
std::cout << "无法打开文件" << std::endl;
}
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!