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

运行结果:

今日思维导图

相关推荐
肆忆_12 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星16 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛2 天前
delete又未完全delete
c++
端平入洛3 天前
auto有时不auto
c++
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc