封裝一個學生的類,定義一個學生這樣類的vector容器, 里面存放學生對象(至少3個)
再把該容器中的對象,保存到文件中。
再把這些學生從文件中讀取出來,放入另一個容器中并且遍歷輸出該容器里的學生。
#include <iostream>
#include <vector>
#include <list>
#include <fstream>using 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()
{//數據寫入vectorvector<Stu> v;Stu s[3];s[0] = {"張三", 20, 70};s[1] = {"李四", 21, 80};s[2] = {"王五", 22, 90};for(int i=0; i<3; 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 i=0; i<3; i++){ofs << s[i] << endl;}ofs.close();//讀文件,list獲取list<Stu> 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;
}