/* 封装一个学生的类, 定义一个学生类的vector容器, 里面存放学生对象(至少3个)
再把该容器中的对象保存到文件中
再把这些学生从文件中读取出来, 放入另一个容器中并且遍历输出该容器里的学生 */
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
class Student
{
friend ifstream &operator>>(ifstream &ifs, Student &stu);
friend ofstream &operator<<(ofstream &ofs, const Student &stu);
friend ostream &operator<<(ostream &cout, const Student &stu);
private:
string name;
int age;
public:
Student() {}
Student(string n, int a) : name(n), age(a) {}
};
ofstream &operator<<(ofstream &ofs, const Student &stu)
{
ofs << "姓名: " << stu.name << " 年龄: " << stu.age << endl;
return ofs;
}
ostream &operator<<(ostream &cout, const Student &stu)
{
cout << "姓名: " << stu.name << " 年龄: " << stu.age << endl;
return cout;
}
ifstream &operator>>(ifstream &ifs, Student &stu)
{
char buf[50];
ifs >> buf >> stu.name >> buf >> stu.age;
return ifs;
}
int main()
{
vector<Student> v;
v.push_back(Student("张三", 18));
v.push_back(Student("李四", 17));
v.push_back(Student("王五", 20));
ofstream ofs; // 创建写类流对象
ofs.open("D:/HQYJ/C++_code/stu.txt", ios::out); // 打开文件
vector<Student>::iterator i; // 迭代器
for (i = v.begin(); i != v.end(); i++) // 写入数据
{
ofs << *i;
}
ofs.close(); // 关闭文件
ifstream ifs; // 创建读类流对象
ifs.open("D:/HQYJ/C++_code/stu.txt", ios::in); // 打开文件
vector<Student> vv;
Student stu;
while (ifs >> stu)
{
vv.push_back(stu);
}
ifs.close(); // 关闭文件
for (i = vv.begin(); i != vv.end(); i++)
{
cout << *i;
}
return 0;
}
10.13 作业
最新推荐文章于 2024-11-09 20:38:27 发布