#include <iostream>
#include <vector>
#include <fstream>

using namespace std;
class Stu
{
private:
    string name;
    int age;
public:
    Stu(){}
    Stu(string name,int age):name(name),age(age){}
    void show()
    {
        cout << name << " " << age;
    }
    void WriteToFile(ofstream &ofs)
    {
        ofs << name << " " << age <<endl;
    }
    void ReadFromFile(ifstream &ifs)
    {
        ifs >> name >> age;
    }

    string getName()const{return name;}
    int getAge()const{return age;}
};
void printVector(vector<Stu> &other)
{
    //迭代器==指针
    vector<Stu>::iterator iter;
    for(iter= other.begin();iter!=other.end();iter++)
    {
         iter->show();
         cout << endl;
    }
}

int main()
{
    vector<Stu> v;
    v.push_back(Stu("张三",18));
    v.push_back(Stu("张鸿儒",20));
    v.push_back(Stu("李四",18));

    printVector(v);

    //创建流对象
    ofstream ofs;
    //打开文件
    ofs.open("C:/Users/Lenovo/Desktop/25072C++/Student.txt",ios::out);

    if(!ofs.is_open())
    {
        cout << "文件打开失败!" << endl;
        return -1;
    }
    //写入数据
    ofs << v.size() << endl;
    vector<Stu>::iterator iter;
    for(iter=v.begin();iter!=v.end();iter++)
    {
        iter->WriteToFile(ofs);
    }

    ofs.close();
    cout << "学生数据已经保存到文件!" << endl;


    //从文件中读取到另一个容器
    vector<Stu> s2;
    //创建流对象
    ifstream ifs;
    //打开文件
    ifs.open("C:/Users/Lenovo/Desktop/25072C++/Student.txt",ios::in);
    if(ifs.is_open()==0)
    {
        cout << "打开文件失败" << endl;
    }

    //读取学生数量
    int count;
    ifs >> count;
    ifs.ignore();
    for(int i=0;i<count;i++)
    {
        Stu s;
        s.ReadFromFile(ifs);
        s2.push_back(s);
    }

    //关闭文件
    ifs.close();

    printVector(s2);








    return 0;
}

Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐