#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
class Stu
{
friend void printVector(vector<Stu> &v);
friend void Read_txt(vector<Stu> &v);
friend void Print(vector<Stu> &v);
private:
string name;
int age;
int high;
public:
Stu() {}
Stu(string n,int a,int h):name(n),age(a),high(h){}
};
void printVector(vector<Stu> &v)
{
ofstream ofs;
ofs.open("D:/stu.txt",ios::out);
vector<Stu>::iterator iter;
for(iter = v.begin(); iter !=v.end(); iter++)
{
ofs << iter->name << " ";
ofs << iter->age << " ";
ofs << iter->high << '\n';
}
ofs.close();
}
void Read_txt(vector<Stu> &v)
{
ifstream ifs;
ifs.open("D:/stu.txt",ios::in);
char buff[1024];
int buf;
Stu s;
while(ifs>>buff)
{
s.name = buff;
ifs >> buf;
s.age = buf;
ifs >> buf;
s.high = buf;
v.push_back(s);
}
ifs.close();
}
void Print(vector<Stu> &v)
{
vector<Stu>::iterator iter;
for(iter = v.begin(); iter !=v.end(); iter++)
{
cout << iter->name << " ";
cout << iter->age << " ";
cout << iter->high << '\n';
}
}
int main()
{
Stu stu1("张三",12,187);
Stu stu2("李四",15,177);
Stu stu3("王五",19,180);
vector<Stu> s1;
s1.push_back(stu1);
s1.push_back(stu2);
s1.push_back(stu3);
printVector(s1);
vector<Stu> vec;
Read_txt(vec);
Print(vec);
return 0;
}
学生类存储容器
最新推荐文章于 2024-06-16 19:40:15 发布