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;
}

效果图:

相关推荐
ShineWinsu5 小时前
对于C++:IO流状态的详细解析
c++·面试·io·cin·io流状态·goodbit·failbit
Lzg_na6 小时前
constexpr的优势
c++
王维同学7 小时前
进程模块枚举、映像身份与线程启动地址关联
c++·windows·安全
hold?fish:palm7 小时前
24 回文链表
数据结构·c++·链表
举手8 小时前
Dispatcher模块剖析
linux·c++
何事误红尘8 小时前
全志A40i学习笔记():开发资料、启用串口
学习
for_ever_love__8 小时前
python基础语法学习: 异常的传递性
开发语言·python·学习
PC2005-cloud8 小时前
DeepSeek Harness 创建 skill 指南:结构、安装、使用
笔记·学习
依然鸣9 小时前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论
YM52e9 小时前
分页查询的基石:ArkTS 为鸿蒙商品列表设计 LIMIT/OFFSET 的表
android·学习·华为·harmonyos