[英]Reading objects from file in c++
我創建了一個類,用於存儲用戶的詳細信息,例如帳號,姓名余額等。我正在將該類的對象寫入文件。 當我從文件中讀取時,我沒有得到正確的輸出。 如果輸入了2個人的詳細信息,那么我將兩次獲得第二個人的詳細信息。 這是代碼。
#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();
}
這是為什么循環條件內的iostream :: eof被認為是錯誤的嗎? ,但測試略有不同
while(fin)
{
fin.read((char*)this, sizeof(this));
this->accsummary();
}
在將數據添加到摘要之前,您無需測試read
是否成功。 這將使循環中的最后+1輪第二次添加最后一個數據。
在您未成功讀取之前, while(fin)
不會終止循環。 那一輪為時已晚。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.