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 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真