li-heng 2023-04-05 13:41 采纳率: 81.5%
浏览 67
已结题

C++ std::wofstream 类输出中内容到文件中失败

求一个使用 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;
}


  • 写回答

2条回答 默认 最新

  • 社区专家-Monster-XH 2023-04-05 14:12
    关注

    基于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;
    }
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月13日
  • 已采纳回答 4月5日
  • 修改了问题 4月5日
  • 修改了问题 4月5日
  • 展开全部