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

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日
  • 展开全部

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化