#include <iostream>#include <fstream>
#include <vector>
#include <string>
#include <iostream>
using
namespace std;
class CPeople
{
public:
void showinformation();
CPeople(string name,int age);
void getinformation();
private:
int m_age;
string m_name;
};
void CPeople::getinformation()
{
cout <<"enter name: ";
cin >>m_name;
cout <<"enter age: ";
cin >>m_age;
}
CPeople::CPeople(string name, int age)
{
m_name = name;
m_age = age;
}
void CPeople::showinformation(){ cout <<"name: "
<<m_name;
cout <<" age: "
<<m_age <<endl;
}
int main()
{
ifstream infile;
ofstream outfile;
string choice;
vector<CPeople> vpeople;
CPeople peo("zhangsan",20);
// outfile.open("people.txt",ios_base::out|ios_base::binary);
// do
// {
// peo.getinformation();
// vpeople.push_back(peo);
// outfile.write(reinterpret_cast<char *>(&peo),sizeof(peo));
// cout <<"continue?[yes/no]: ";
// cin >>choice;
// cin.sync();
// } while (choice[0] != 'n');
// outfile.close();
// for (vector<CPeople>::size_type ix = 0; ix < vpeople.size(); ++ix)
// {
// vpeople[ix].showinformation();
// }
//不注释以上代码 程序可以正确执行 当注释时 在文件中读时就出错了
infile.open("people.txt",ios_base::in|ios_base::binary);
while (infile.peek()!=EOF)
{
infile.read(reinterpret_cast<char
*>(&peo),sizeof(peo));
peo.showinformation();
}
infile.close();
return
0;
} |