手机在线建站,深圳设计展,金华网站建设yw126,祝贺网站上线封装一个学生的类#xff0c;定义一个学生这样类的vector容器, 里面存放学生对象#xff08;至少3个#xff09;再把该容器中的对象#xff0c;保存到文件中。再把这些学生从文件中读取出来#xff0c;放入另一个容器中并且遍历输出该容器里的学生。#include iostream…封装一个学生的类定义一个学生这样类的vector容器, 里面存放学生对象至少3个再把该容器中的对象保存到文件中。再把这些学生从文件中读取出来放入另一个容器中并且遍历输出该容器里的学生。
#include iostream
#include vector
#include list
#include fstreamusing namespace std;class Stu
{friend ostream operator(ostream os, const Stu stu);friend istream operator(istream ifs, Stu temp);
private:string name;int age;double score;
public:Stu(){}Stu(string name, int age, double score):name(name), age(age), score(score){}void show(){cout name age score endl;}
};ostream operator(ostream ofs, const Stu stu)
{ofs stu.name \t stu.age \t stu.score endl;return ofs;
}istream operator(istream ifs, Stu temp)
{ifs temp.name;ifs temp.age;ifs temp.score;return ifs;
}int main()
{//数据写入vectorvectorStu v;Stu s[3];s[0] {张三, 20, 70};s[1] {李四, 21, 80};s[2] {王五, 22, 90};for(int i0; i3; i){v.push_back(s[i]);}//写入文件ofstream ofs;ofs.open(D:\\Cpp_code\\day8\\Stu.txt, ios::out | ios::trunc);ofs 姓名\t年龄\t成绩 endl;for(int i0; i3; i){ofs s[i] endl;}ofs.close();//读文件list获取listStu l;ifstream ifs;ifs.open(D:\\Cpp_code\\day8\\Stu.txt, ios::in);//获取标题行string header;getline(ifs,header);//获取数据信息Stu temp;while(ifs temp){l.push_back(temp);}ifs.close();//输出listcout 从文件中读取的学生信息 endl;cout header endl;for(const Stu student: l){cout student;}return 0;
}