You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++写入对象到文件出现乱码问题求助

问题分析与解决方案

问题根源

  1. 未初始化的垃圾数据:你的代码中Events类的eventName是长度为90的char数组,通过cin输入的字符串长度远小于90,数组中未被覆盖的区域是未初始化的随机垃圾数据。使用write写入整个对象时,这些垃圾数据会被一并写入文件,导致乱码。
  2. 二进制写入与文本解析不匹配:直接以二进制方式写入整个对象,文件中包含数组的全部90字节(包括垃圾数据),文本编辑器解析这些二进制内容时,未初始化的字节多为不可打印字符,表现为乱码。

解决方案

方案1:改用std::string存储(推荐)

用std::string代替char数组,它会自动管理有效字符串长度,写入时只会输出实际输入的内容,不会包含多余数据:

#include<bits/stdc++.h>
using namespace std;

class Events{
    string eventName;
    
public:
    void setEventName(){
        cout<<"set event name ";
        cin>>eventName;
    }
    
    const string& getEventName() const {
        return eventName;
    }
};

class EventFunctions:public Events{
public:
    void WriteEvent(){
        Events obj;
        obj.setEventName();
        ofstream outf("hello.txt");
        outf << obj.getEventName();
        outf.close();
    }
};

int main(){
    EventFunctions ee;
    ee.WriteEvent();        
}

方案2:只写入eventName的有效部分

如果坚持使用char数组,可只写入到字符串结束符\0的位置,避免垃圾数据被写入:

// 修改Events类,开放eventName的访问权限或添加get方法
class Events{
public: // 将eventName设为public,或添加get方法
    char eventName[90];
    
    void setEventName(){
        cout<<"set event name ";
        cin>>eventName;
    }
};

// 在WriteEvent中修改写入逻辑
void WriteEvent(){
    Events obj;
    obj.setEventName();
    ofstream outf("hello.txt");
    // 只写入有效字符串长度(包含结束符)
    outf.write(obj.eventName, strlen(obj.eventName));
    // 或者直接用流输出,自动处理结束符
    // outf << obj.eventName;
    outf.close();
}

方案3:初始化数组避免垃圾数据

在Events的构造函数中初始化数组为全0,这样未被覆盖的区域都是空字节,不会出现随机乱码(但仍会有多余空字节):

class Events{
    char eventName[90];
public:
    Events(){
        // 将数组全部初始化为0
        memset(eventName, 0, sizeof(eventName));
    }
    
    void setEventName(){
        cout<<"set event name ";
        cin>>eventName;
    }
};

额外说明

如果需要后续从文件中读取还原对象,不建议直接二进制写入整个对象——这种方式会受内存对齐、编译器版本影响,跨环境读取容易出错。更可靠的方式是将对象成员按文本或结构化格式(如JSON)序列化后写入。

内容的提问来源于stack exchange,提问作者xAdvitya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 20:15:41