65,211
社区成员
发帖
与我相关
我的任务
分享//我感觉楼主最好这样写:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Account
{
friend ostream & operator<< (ostream& os, const Account & person);
friend istream & operator>> (istream& in, Account & person);
string name;
string id;
string password;
double money;
public:
Account(){};
Account(string n, string i, string p, double m=0)
{
name = n;
id = i;
password = p;
money = m;
}
};
ostream& operator << (ostream& os, const Account & person)
{
os<<person.name<<endl;
os<<person.id<<endl;
os<<person.password<<endl;
os<<person.money<<endl;
return os; //返回...
}
istream& operator >> (istream& in, Account & person)
{
in >> person.name;
in >> person.id;
in >> person.password;
in >> person.money;
return in; //返回...
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
Account a("111", "as", "123", 12.3), b("222", "sa", "321", 32.1);
fstream fout;
fout.open("c:\\a.txt", ios::out|ios::binary|ios::app);
//char * c;
//file.write((char*)&a, sizeof(Account));
//file.write((char*)&b, sizeof(Account));
if (!fout.is_open())
{
cerr <<"can't open the file";
return 0;
}
fout << a;
fout << b;
fout.close();
fstream fin;
fin.open("c:\\a.txt", ios::in|ios::binary);
while (!fin.eof())
{
Account c;
//file.read(c, sizeof(Account));
fin >> c;
//cout << c;
cout << c;
}
fin.close();
return 0;
}