0
我創建了一個類,用於存儲用戶的詳細信息,如帳號,名稱平衡等。我正在將此類的對象寫入文件。當我從文件中讀取時,我沒有得到正確的輸出。如果一個人輸入了兩個人的詳細信息,那麼我將獲得第二個人的詳細信息兩次。這是代碼。從C++的文件中讀取對象
#include <fstream>
#include <string>
#include <ctime>
# include <conio.h>
#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace std;
class User
{
int acctype[2] = {0,0}; // acctype[0] = savings account & acctype[1] = current account
string name = "NULL";
string address = "NULL";
string dob = "NULL";
long int sbal = 0;
long int cbal = 0;
long int accno = 0;
string password;
int aod = 0; // account opening date
int aom = 0; // account opening month
int aoy = 0; // account opening year
public:
void input()
{
system("cls");
cin.clear();
char type,ch;
cout << "Enter you name\n";
getline(cin,name);
cout << "Enter your address\n";
getline(cin,address);
cout << "Enter your date of birth(dd/mm/yyyy)\n";
getline(cin,dob);
cout << "Enter your account type(s = savings, c = current)\n";
cin >> type;
if(type == 's')
{
acctype[0] = 1;
cout << "Enter your savings account balance\n";
cin >> sbal;
}
else if(type == 'c')
{
acctype[1] = 1;
cout << "Enter your current account balance\n";
cin >> cbal;
}
pass:
cout << "\nChoose a password(8-16 characters)\n";
// to display * in place of the entered character for the password
ch = _getch();
while(ch != 13)// to check for return input
{
password.push_back(ch);
cout << "*";
ch = _getch();
}
if(password.size() < 8 || password.size() > 16)
goto pass;
//store the account opening date
time_t now = time(0);
tm *ltm = localtime(&now);
aod = ltm->tm_mday;
aom = 1 + ltm->tm_mon;
aoy = 1900 + ltm->tm_year;
cin.ignore(10000,'\n');
}
void datawrite()
{
//store the data in the file
ofstream fout;
fout.open("database.txt", ios_base::app);
if(!fout.is_open())
{
cout << "\nCannot open file! Aborting";
exit(0);
}
fout.write((char*) this, sizeof(this));
fout.close();
}
int dataread()
{
ifstream fin;
fin.open("database.txt", ios_base::in);
if(!fin.is_open())
{
cout << "\nCannot open file! Aborting";
exit(0);
}
fin.seekg(0);
fin.read((char*)this, sizeof(this));
while(fin)
{
//system("cls");
fin.read((char*)this, sizeof(this));
this->accsummary();
}
fin.close();
}
void accsummary()
{
//system("cls");
cout << "\n\t\tACCOUNT SUMMARY\n";
cout << "\nName : " << name;
cout << "\nAccount NUmber : " << accno;
cout << "\nDate of birth : " << dob;
cout << "\nAddress : " << address;
cout << "\nAccount opening date : " << aod << "/" << aom << "/" << aoy;
if(acctype[0] == 1)
cout << "\nSavings Account Balance : " << sbal;
if(acctype[1] == 1)
cout << "\nCurrent Account Balance : " << cbal;
}
};
int main()
{
User u;
u.input();
u.datawrite();
u.dataread();
}