Day8 C++
封装一个学生的类,定义一个学生这样类的vector容器, 里面存放学生对象(至少3个)
再把该容器中的对象,保存到文件中。
再把这些学生从文件中读取出来,放入另一个容器中并且遍历输出该容器里的学生。
#include <iostream>
#include <vector>
#include <fstream>using namespace std;
//学生类
class Student
{
private:string name;int age;double socre;
public://无参构造函数Student(){}//有参构造Student(string name,int age,double socre):name(name),age(age),socre(socre){}void show(){cout<<"姓名:"<<name<<"年龄:"<<age<<"成绩"<<socre<<endl;}//序列化到文件void serialize(ofstream& ofs)const{ofs<<name<<" "<<age<<" "<<socre<<endl;}
};
int main()
{//创建学生容器vector<Student>students;students.push_back(Student("张三",20,90));students.push_back(Student("李四",18,91));students.push_back(Student("王五",21,88));students.push_back(Student("老六",22,92));ofstream ofs;ofs.open("D:/QTC++/day8/work/Stu.txt",ios::out);for(auto it=students.begin();it!=students.end();it++){it->serialize(ofs);}ofs.close();ifstream ifs;ifs.open("D:/QTC++/day8/work/Stu.txt",ios::in);string line;while (getline(ifs, line)){cout << line << endl;}ifs.close();return 0;
}