8.29作业

封装一个学生的类,定义一个学生这样类的vector容器, 里面存放学生对象(至少3个)

再把该容器中的对象,保存到文件中。

再把这些学生从文件中读取出来,放入另一个容器中并且遍历输出该容器里的学生。

#include <iostream>
#include<vector>
#include<fstream>
using namespace std;
class Student
{
    friend ostream &operator<<(ostream&ofs, const Student&s1);
    friend istream &operator>>(istream&ifs, Student&s1);
private:
    string name;
    int age;
    string sex;
public:
    Student() {}
    Student(string name,int age,string sex):name(name),age(age),sex(sex)
    {}
    void all(string name,int age,string sex)
    {
        this->name=name;
        this->age=age;
        this->sex=sex;
    }
};
ostream &operator<<(ostream&ofs,const Student&s1)
{
    ofs << s1.name<< " ";
    ofs << s1.age<< " ";
    ofs << s1.sex;
    return ofs;
}

void insertVector(vector<Student>&students,ofstream &ofs)
{
    vector<Student>::iterator iter;
    for(iter=students.begin();iter!=students.end();iter++)
    {
        ofs << *iter << endl;
    }
}
istream &operator>>(istream&ifs, Student&s1)
{
    ifs >> s1.name;
    ifs >> s1.age;
    ifs >> s1.sex;
    return ifs;
}
int main()
{
    vector<Student> students;
    Student s1("zhangsan",12,"ss");
    students.push_back(s1);
    Student s2("lisi",13,"aa");
    students.push_back(s2);
    Student s3("wangwu",14,"cc");
    students.push_back(s3);
    ofstream ofs;
    ofs.open("C:/Users/wgh/Documents/qtwenjian/1.txt",ios::out);
    insertVector(students,ofs);
    ofs.close();
    ifstream ifs;
    ifs.open("C:/Users/wgh/Documents/qtwenjian/1.txt",ios::in);
    vector<Student> students1;
    Student s4;
    while (ifs>>s4) {
        students1.push_back(s4);
    }
    vector<Student>::iterator iter;
    for(iter=students1.begin();iter!=students1.end();iter++)
    {
        cout << *iter << endl;
    }
    ifs.close();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值