C++学习day7

一、思维导图

二、作业试编程:

封装一个学生的类,定义一个学生这样类的vector容器,里面存放学生对象(至少3个)再把该容器中的对象,保存到文件中。 封装一个学生的类,定义一个学生这样类的载体容器,里面存放学生对象(至少3个)再把该容器中的对象,保存到文件中.

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

cpp 复制代码
#include <iostream>
#include<vector>
#include<fstream>//包含头文件

using namespace std;
class Stu
{
public:
    string name;
    int age;
public:
    Stu(){};
    Stu(string n,int a):name(n),age(a){};//有参构造函数

};
//容器的大小empty()
//写入数据到文件中
void printfVector(vector<Stu> &v)//算法(自己封装的算法&引入外部对象)
{
    //创建流对象
    ofstream ofs;
    ofs.open("D:/day7_code/tex1.tex",ios::out);
    //打开文件
    vector<Stu>::iterator iter;//迭代器
    for(iter = v.begin();iter< v.end();iter++)
    {
        //写入文件
        ofs << iter->name << " " << iter->age  << endl;
    }
    cout << endl;

}
void readVector(vector<Stu>& v)
{
    ifstream ifs;
    ifs.open("D:\\day7_code\\tex1.tex", ios::in);

    vector<Stu>::iterator iter;
    for (iter = v.begin(); iter != v.end(); iter++)
    {
//        string line;
//        getline(ifs, line);
//        cout << line << endl;
        char buff[1024];
        while(ifs >> buff)
        {
            cout << buff << endl;//每次读到空格或者换行截止
        }

    }

    cout << endl;
}
int main()
{
    //创建一个容器

    Stu s("zhangsan",34);
    Stu s1("lisi",18);
    Stu s2("wangwu",33);

    vector<Stu> v;
    v.push_back(s);
    v.push_back(s1);
    v.push_back(s2);//将数据存到容器中
    printfVector(v);
    readVector(v);



    return 0;
}

效果图:

相关推荐
charlie11451419110 分钟前
Cinux: 为大内核铺路
开发语言·c++·操作系统·现代c++
米罗篮2 小时前
矩阵快速幂 (Exponentiation By Squaring Applied To Matrices)
c++·线性代数·算法·矩阵
肖爱Kun3 小时前
C++设计策略模式
开发语言·c++·策略模式
胡渠洋3 小时前
postman学习
学习·测试工具·postman
炸膛坦客4 小时前
单片机/C/C++八股:(二十四)编译文件( .bin 和 .hex ,包括 .elf 和 .axf )
c语言·c++·单片机
Amazing_Cacao5 小时前
CFCA精品可可产区风土解析(美洲):无情打破风味堆叠假象,建立时间轴上的层次动态阅读系统
学习
cpp_25015 小时前
P10098 [ROIR 2023] 地铁建设 (Day 2)
数据结构·c++·算法·贪心·二分答案·洛谷题解
六点_dn5 小时前
Linux学习笔记-shell运算符
linux·笔记·学习
其实防守也摸鱼5 小时前
渗透--损坏的对象级别鉴权漏洞(Broken Object Level Authorization, BOLA)
大数据·网络·数据库·学习·tcp/ip·安全·安全威胁分析
hehelm5 小时前
IO 多路复用 — Reactor
linux·服务器·网络·数据库·c++