//设计一个person类,从键盘输入每个人的姓名、身份证号、年龄、地址等数据,并将每个人的信息保存在目录
//C:下的二进制文件person.dat中,然后将文件中的个人信息读出来,保存在vector类型的向量中并显示出来
//Eg9-8.cpp
#include"iostream"
#include"vector"
#include"string"
#include"fstream"
#include"stdlib.h"
using namespace std;
class Person {
public:
Person() {};
Person(string _name, string _id, string _age, string _addr){
m_strName = _name;
m_strId = _id;
m_strAge = _age;
m_strAddr = _addr;
}
void display() {
cout << m_strName << "\t" << m_strId << "\t" << m_strAge << "\t" << m_strAddr << endl;
}
private:
string m_strName;
string m_strId;
string m_strAge;
string m_strAddr;
};
void main() {
vector<Person>p;
vector<Person>::iterator q;
char ch;
ofstream out("c:\\person.dat", ios::out | ios::app | ios::binary);
string name;
string id;
string age;
string addr;
cout << "-----输入个人档案-----" << endl << endl;
do {
cout << "姓名:"; cin >> name;
cout << "身份证号:"; cin >> id;
cout << "年龄:"; cin >> age;
cout << "地址:"; cin >> addr;
Person s1(name, id, age, addr); //调用构造函数创建一个对象s1
out.write((char*)&s1,sizeof(s1));//函数write()一次插入n个字节到输出流中,即一次写入n字节内容到文件中
cout << "Enter another person (y/n)?"; cin >> ch;
} while (ch == 'y');
out.close();
fstream in("c:\\person.dat", ios::in | ios::binary);
Person s2;
/*do {
in.read((char*)&s2, sizeof(s2));
p.push_back(s2);
} while (!in.eof());*/
in.read((char*)&s2,sizeof(s2));
while (!in.eof())
{
p.push_back(s2);
in.read((char*)&s2, sizeof(s2));
}
in.close();
cout << "/n-----输入个人档案-----" << endl << endl;
//q = p.begin(),
for(q = p.begin(); q != p.end(); q++)
{
(*q).display();
}
system("pause");
}
相关分类