封装一个学生的类,定义一个学生这样类的vector容器, 里面存放学生对象(至少3个)再把该容器中的对象,保存到文件中。 再把这些学生从文件中读取出来,放入另一个容器中并且遍历输出该容
·
#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;
}
更多推荐


所有评论(0)