封装一个学生的类,定义一个学生这样类的vector容器, 里面存放学生对象(至少3个)
再把该容器中的对象,保存到文件中。
再把这些学生从文件中读取出来,放入另一个容器中并且遍历输出该容器里的学生。
#include
#include
#include
using namespace std;
class Student
{
friend ostream &operator<<(ostream&ofs, const Student&s1);
friend istream &operator>>(istream&ifs, Student&s1);
private:
string name;
int age;
string sex;
public:
Student() {}
Student(string name,int age,string sex):name(name),age(age),sex(sex)
{}
void all(string name,int age,string sex)
{
this->name=name;
this->age=age;
this->sex=sex;
}
};
ostream &operator<<(ostream&ofs,const Student&s1)
{
ofs << s1.name<< " ";
ofs << s1.age<< " ";
ofs << s1.sex;
return ofs;
}
void insertVector(vector&students,ofstream &ofs)
{
vector::iterator iter;
for(iter=students.begin();iter!=students.end();iter++)
{
ofs << *iter << endl;
}
}
istream &operator>>(istream&ifs, Student&s1)
{
ifs >> s1.name;
ifs >> s1.age;
ifs >> s1.sex;
return ifs;
}
int main()
{
vector students;
Student s1("zhangsan",12,"ss");
students.push_back(s1);
Student s2("lisi",13,"aa");
students.push_back(s2);
Student s3("wangwu",14,"cc");
students.push_back(s3);
ofstream ofs;
ofs.open("C:/Users/wgh/Documents/qtwenjian/1.txt",ios::out);
insertVector(students,ofs);
ofs.close();
ifstream ifs;
ifs.open("C:/Users/wgh/Documents/qtwenjian/1.txt",ios::in);
vector students1;
Student s4;
while (ifs>>s4) {
students1.push_back(s4);
}
vector::iterator iter;
for(iter=students1.begin();iter!=students1.end();iter++)
{
cout << *iter << endl;
}
ifs.close();
return 0;
}