25.9.8 C++day8作业
一、思维导图
二、封装一个学生的类,定义一个学生这样类的vector容器, 里面存放学生对象(至少3个)
再把该容器中的对象,保存到文件中。
再把这些学生从文件中读取出来,放入另一个容器中并且遍历输出该容器里的学生。
#include <iostream>
#include <vector>
#include<fstream>using namespace std;class Stu
{friend ostream& operator<<(ostream& os, const Stu& student);friend istream& operator>>(istream& is, Stu& student);string name;int age;public :Stu(){}Stu(string name,int age) : name(name),age(age){}string getName() const{return name;}int getAge() const{return age;}};ostream& operator<<(ostream& os, const Stu& student) {os << student.name << " " << student.age;return os;}
istream& operator>>(istream& is, Stu& student) {is >> student.name >> student.age;return is;}int main()
{Stu s1("zzh",22);Stu s2("lrh",22);Stu s3("zry",22);vector<Stu> s;s.push_back(s1);s.push_back(s2);s.push_back(s3);ofstream ofs;ofs.open("D:/QT/documents/day8/Stu.txt",ios::out);for (const auto& student : s){ofs << student << endl;}ofs.close();vector<Stu> students;ifstream ifs;ifs.open("D:/QT/documents/day8/Stu.txt",ios::in);Stu temp;while (ifs >> temp) {students.push_back(temp);}ifs.close();cout << "从文件中读取的学生信息:" << endl;for (const auto& student : students) {cout << "姓名: " << student.getName()<< ", 年龄: " << student.getAge() << endl;}return 0;
}