DAY 7 C++

#include 
#include 
#include 
//试编程:
//封装一个学生的类,定义一个学生这样类的vector容器,  里面存放学生对象(至少3个)
//再把该容器中的对象,保存到文件中。 
//再把这些学生从文件中读取出来,放入另一个容器中并且遍历输出该容器里的学生。
using namespace std;
class Stu  //创建学生类
{
public:  //成员定义2个
    string name;
    int id;
public:
    Stu(){}
    Stu(string n,int id):name(n),id(id)//类中有参构造函数
    {}
    void show()
    {
        cout << name << "  " << id << endl;
    }
};
void printvetor(vector v)//写入数据至文件中
{
    ofstream ofs;
    ofs.open("C:/Users/26413/Desktop/stu.txt",ios::out);
    vector::iterator iter;
    for (iter=v.begin();iter!=v.end();iter++)
    {
        ofs << iter->name  << " " << iter->id <> buff)//循环读取
     {
         cout << buff << endl;//读出到buff,再从buff中终端输出
     }
     ifs.close();//关闭读取对象,防止资源流失造成资源浪费
}

int main()
{
    vector S1;//设立迭代器用来放学生类(动态数组)
    Stu s1("shanghong",10);//定义类对象S1并初始化
    Stu s2("小明",18);
    Stu s3("方世玉",18);
    S1.push_back(s1);
    S1.push_back(s2);//加入学生信息

    S1.push_back(s3);
    printvetor(S1); //写入
    readvector();//读出
    return 0;
}

DAY 7 C++_第1张图片

你可能感兴趣的:(c++)