C++中的class信息如何写入txt文件中
时间: 2024-03-23 20:41:53 浏览: 124
在C++中将class信息写入txt文件中可以通过以下步骤实现:
1. 定义一个class类。
2. 将需要保存的class信息存储在对象中。
3. 使用文件操作相关函数打开文件,将需要保存的信息写入txt文件中。
下面是一个简单的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// 定义一个class类
class Student {
public:
string name;
int age;
string gender;
int score;
};
int main() {
// 创建一个Student对象
Student stu;
stu.name = "Tom";
stu.age = 18;
stu.gender = "male";
stu.score = 90;
// 打开文件
ofstream ofs("student.txt");
if (!ofs) {
cout << "文件打开失败!" << endl;
return 1;
}
// 将对象中的信息写入txt文件中
ofs << "姓名:" << stu.name << "\n";
ofs << "年龄:" << stu.age << "\n";
ofs << "性别:" << stu.gender << "\n";
ofs << "分数:" << stu.score << "\n";
// 关闭文件
ofs.close();
return 0;
}
```
运行上述代码后,会在程序所在目录下生成一个名为“student.txt”的文件,其中保存了Student对象的信息。
阅读全文
相关推荐
















