C++day8作业

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

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

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

cpp 复制代码
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;


class Stu
{
private:
    string name;
    int age;
    int id;
public:
    Stu(){}
    Stu(string name,int age,int id):name(name),age(age),id(id){}
    string wri()const
    {
        return name + " " + to_string(age) + " " + to_string(id);
    }
};
int main()
{
    vector<Stu> stus;
    stus.push_back(Stu("张三",20,1001));
    stus.push_back(Stu("李四",21,1002));
    stus.push_back(Stu("王五",20,1003));
    ofstream ofs;
    try {
        ofs.open("D:/QT/QT/day8/aaa",ios::out);
        if(!ofs.is_open())
        {
            throw -1;
        }
    } catch (int &e) {
        if(e==-1)
        {
            cout << "打开失败" << endl;
        }
    }

    for(auto &stu : stus)
    {
        ofs << stu.wri() <<endl;
    }
    ofs.close();

    ifstream ifs;
    try {
        ifs.open("D:/QT/QT/day8/aaa",ios::in);
        if(!ifs.is_open())
        {
            throw -1;
        }
    } catch (int &c) {
        if(c==-1)
        {
            cout << "打开失败" << endl;
        }
    }

    char buf[1024];
    while(ifs>>buf)
    {
        cout << buf << endl;
    }

    ifs.close();
    return 0;
}

实现list的相关函数

cpp 复制代码
#include <iostream>
#include <list>
using namespace std;

void printfList(list<int> &lst)
{
    list<int>::iterator iter;
    for(iter = lst.begin(); iter != lst.end();iter++)
    {
        cout << *iter << " ";
    }
    cout << endl;
}

int main()
{
    list<int> lst;
    lst.push_back(10);
    lst.push_back(20);
    lst.push_back(30);
    lst.push_back(40);
    lst.push_back(50);

    printfList(lst);

    list<int>  lst1;
    lst1=lst;
    printfList(lst1);
    list<int>  lst2(lst1);
    printfList(lst2);
    list<int> lst3;
    lst3.assign(lst2.begin(),lst2.end());
    printfList(lst3);

    if(!lst.empty())
    {
        cout << "aaa" <<endl;
        cout << lst.size() << endl;
    }
    cout << "===============" <<endl;
    lst.resize(6,5);
    printfList(lst);
    cout << "===============" <<endl;
    printfList(lst1);
    lst1.pop_back();
    printfList(lst1);
    cout << "===============" <<endl;
    printfList(lst2);
    lst2.insert(lst2.begin(),90);
    printfList(lst2);
    cout << "===============" <<endl;
    printfList(lst3);
    lst3.clear();
    printfList(lst3);
    return 0;
}

思维导图

相关推荐
小许好楠8 分钟前
java开发工程师-学习方式
java·开发语言·学习
xwill*11 分钟前
python 字符串拼接
linux·windows·python
我是苏苏18 分钟前
Web开发:Windows系统中使用GUI界面或cmd命令设置防火墙规则
windows
superman超哥24 分钟前
仓颉锁竞争优化深度解析
c语言·开发语言·c++·python·仓颉
Halo_tjn25 分钟前
基于 IO 流实现文件操作的专项实验
java·开发语言
一晌小贪欢26 分钟前
【Python办公自动化】Python办公自动化常用库新手指南
开发语言·python·python自动化办公·python3·python办公自动化·python办公
业精于勤的牙34 分钟前
最长特殊序列(二)
java·开发语言·算法
yong999044 分钟前
C#实现OPC客户端与S7-1200 PLC的通信
开发语言·网络·算法·c#
charlie1145141911 小时前
快速在WSL上开发一般的C++上位机程序
开发语言·c++·笔记·学习·环境配置·工程
仲夏月二十八1 小时前
关于golang中何时使用值对象和指针对象的描述
开发语言·后端·golang