/*
编程题:
封装:学生类,并定义 学生这种类のvector容器, 里面存放学生对象(至少3个);
再把该容器中の对象,保存到文件中;
再把这些学生从文件中读取出来,放入另一个容器中并遍历输出该容器里の学生。
*/
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class Stu //类(学生)————封装
{
public: //数据成员 ×2
string name;
int id;
public:
//无参构造()
Stu(){}
//有参构造():初始化列表
Stu(string n, int i) : name(n), id(i)
{}
void show()
{
cout << "姓名:" << name << "\n" << "学号:" << id << endl;
}
};
void printvetor(vector<Stu> v) //写入数据 至文件中
{
ofstream ofs;
ofs.open("C:/Users/Adam/Desktop/stu.txt", ios::out);
vector<Stu>::iterator iter;
for ( iter=v.begin(); iter!=v.end(); iter++ )
{
ofs << iter->name << " " << iter->id << endl; //学生信息 写入至 文件中
}
ofs.close(); //关闭:写入对象, 防止:资源常开, 保证:资源安全
}
void readvector()
{
ifstream ifs; //定义对象:读取文件
ifs.open("C:/Users/Adam/Desktop/stu.txt", ios::in); //打开文件路径,以读的方式
char buff[1024]; //缓冲区(1KB)
while(ifs >> buff) //循环读取
{
cout << buff << endl; //读出到buff,再从buff中输出至终端
}
ifs.close(); //关闭:读取对象,防止:资源流失造成资源浪费
}
int main()
{
vector<Stu> S1;//设置:迭代器 来存学生类(动态数组)
Stu s1("王思聪", 35);//定义类对象S1并初始化
Stu s2("马云",88);
Stu s3("马化腾",38);
//添加:学生信息
S1.push_back(s1);
S1.push_back(s2);
S1.push_back(s3);
printvetor(S1); //写入
readvector(); //读取
return 0;
}