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

C++使用类对象写入文本文件出现乱码问题求助

解决方法

要让文件显示正常的文本内容,有两种简单可行的方案:

方案1:手动输出类的成员变量

因为name和roll是类的私有成员,我们可以给类加一个专门的输出函数,用来把成员变量写入文件:

#include<iostream>
#include<fstream>
#include<string> // 记得显式包含string头文件,避免编译问题
using namespace std;

class Details {
    string name;
    int roll;
public:
    void get();
    // 添加一个输出成员到流的函数
    void writeToFile(ofstream& out) {
        out << name << endl; // 写入名字,换行
        out << roll << endl; // 写入学号,换行
    }
};

void Details::get() {
    cout<<"Enter name : ";
    cin>>name;
    cout<<"Enter Roll No. : ";
    cin>>roll;
}

int main() {
    Details obj;
    obj.get();
    ofstream outfile("data.txt");
    obj.writeToFile(outfile); // 调用函数写入成员
    outfile.close();
    return 0;
}

运行后打开data.txt,就能看到:

Flash
100

方案2:重载流输出运算符(更符合C++风格)

如果想像输出普通变量一样用outfile << obj;,可以为Details类重载ostream的<<运算符,这样代码会更简洁:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

class Details {
    string name;
    int roll;
public:
    void get();
    // 声明友元函数,让它能访问私有成员
    friend ostream& operator<<(ostream& out, const Details& obj);
};

void Details::get() {
    cout<<"Enter name : ";
    cin>>name;
    cout<<"Enter Roll No. : ";
    cin>>roll;
}

// 定义重载的<<运算符
ostream& operator<<(ostream& out, const Details& obj) {
    out << obj.name << " " << obj.roll; // 用空格分隔,也可以换成endl换行
    return out;
}

int main() {
    Details obj;
    obj.get();
    ofstream outfile("data.txt");
    outfile << obj << endl; // 直接输出对象
    outfile.close();
    return 0;
}

这个版本运行后,data.txt里会显示:Flash 100。


额外小贴士

  • 一定要包含<string>头文件:虽然有些编译器会间接包含,但显式写出来能避免很多奇怪的编译错误。
  • 如果之后需要从文件读回数据,也要用文本方式逐个读取成员变量,别直接读二进制对象(除非你专门做序列化,那是另一种场景啦)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:43:09