C++day07(auto、lambda、类型转换、STL、文件操作)

今日任务

试编程:

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

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

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

代码:

cpp 复制代码
#include <iostream>
#include <vector>
#include <fstream>
#include <cstring>
using namespace std;
class Stu{
private:
    string name;
    int id;
public:
    Stu(){}
    Stu(string name,int id):name(name),id(id){}
    string getName(Stu s){
        return s.name;
    }
    int getId(Stu s){
        return s.id;
    }
};

int main()
{
    //--------------写入
    /*
    vector<Stu> v1;
    Stu stu[3]={
        {"zzz",18},
        {"xxx",58},
        {"sss",24}
    };
    v1.push_back(stu[0]);
    v1.push_back(stu[1]);
    v1.push_back(stu[2]);

//    for(vector<Stu>::iterator iter=v1.begin();iter<v1.end();iter++){
//        cout << iter->getName(*iter) << " " << iter->getId(*iter) <<endl;
//    }

    ofstream os;
    os.open("../stu.txt",ios::out);


    for(vector<Stu>::iterator iter=v1.begin();iter<v1.end();iter++){
        os << iter->getName(*iter) << "|" << iter->getId(*iter) <<endl;
    }
    os.close();
    */
    //--------------读取

    vector<Stu> v2;
    ifstream is;
    is.open("../stu.txt",ios::in);
    char buf[128];
    char n[10];
    int a;

    while(is >> buf){
        //cout << buf <<endl;
        //sscanf(buf,"%s|%d",n,&a);不太行,只能用空格作为分割好像
        char *temp=strtok(buf,"|");
        strcpy(n,temp);//获取第一次分割字符串
        temp = strtok(NULL,"|");//获取第二次
        a=atoi(temp);//将字符串转为整型并返回
        //cout << "n=" << n << " a=" << a <<endl;
        Stu s(n,a);
        v2.push_back(s);
    }


    is.close();
    for(vector<Stu>::iterator iter=v2.begin();iter<v2.end();iter++){
        cout << iter->getName(*iter) << " " << iter->getId(*iter) <<endl;
    }

    return 0;
}

运行结果:

今日思维导图

相关推荐
ankleless7 分钟前
C语言——关于指针(逐渐清晰版)
c语言·开发语言·指针·解引用操作符·c语言基础知识学习
打码农的篮球21 分钟前
STL——list
开发语言·c++·list
lkf1971128 分钟前
商品中心—1.B端建品和C端缓存
开发语言·后端·缓存
渣渣盟1 小时前
JavaScript核心概念全解析
开发语言·javascript·es6
C++ 老炮儿的技术栈1 小时前
在 Scintilla 中为 Squirrel 语言设置语法解析器的方法
linux·运维·c++·git·ubuntu·github·visual studio
java叶新东老师2 小时前
goland编写go语言导入自定义包出现: package xxx is not in GOROOT (/xxx/xxx) 的解决方案
开发语言·后端·golang
@蓝莓果粒茶2 小时前
LeetCode第350题_两个数组的交集II
c++·python·学习·算法·leetcode·职场和发展·c#
檀越剑指大厂2 小时前
【Python系列】Flask 应用中的主动垃圾回收
开发语言·python·flask
檀越剑指大厂2 小时前
【Python系列】使用 memory_profiler 诊断 Flask 应用内存问题
开发语言·python·flask
笠码2 小时前
JVM Java虚拟机
java·开发语言·jvm·垃圾回收