#include "bank.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
using namespace std;
Bank::Bank()
{
}
void Bank::loadBankData(const char* filename)
{
fstream file;
file.open(filename,ifstream::in);
if(!file)
{
cerr << "In load open ./doc/userInfo error!" << endl;
return;
}
string line;
char id[20],name[20];
int pin;
double balance;
while(getline(file,line))
{
istringstream istr(line);
istr >> id >> name >> pin >> balance;
Account act(id,name,pin,balance);
accounts.push_back(act);
}
file.close();
}
void Bank::saveBankData(const char* filename)
{
fstream file;
file.open(filename,ofstream::out|ofstream::binary|ofstream::ate);
if(!file)
{
cerr << "In save open ./doc/userInfo error!" << endl;
return;
}
int i;
for(i=0;i<accounts.size();i++)
{
file << accounts[i].getAccountId() << " "
<< accounts[i].getAccountName() << " "
<< accounts[i].getPasswd() << " "
<< accounts[i].getBalance() << " "
<< endl;
}
file.close();
}
bool Bank::checkPasswd(char* id,int pin)
{
Account *p = getAccount(id);
if(p == NULL)
{
cerr << "Account is not existed!" << endl;
return false;
}
if(pin == p->getPasswd())
return true;
return false;
}
bool Bank::addAccount(char* id,char* name,int pin,double amt)
{
Account act(id,name,pin,amt);
accounts.push_back(act);
return true;
}
bool Bank::delAccount(char* id)
{
Account *p = getAccount(id);
if(p == NULL)
return false;
accounts.erase((vector<Account>::iterator)p);
return true;
}
bool Bank::resetPasswd(char* id,int pin)
{
Account *p = getAccount(id);
if(p == NULL)
return false;
p->setPasswd(pin);
return true;
}
void Bank::displayAllAccount()
{
int i;
for(i=0;i<accounts.size();i++)
{
cout << accounts[i].getAccountId() << "\t"
<< accounts[i].getAccountName() << "\t"
<< accounts[i].getBalance() << "\t"
<< endl;
}
}
void Bank::displayOneAccount(char* id)
{
Account *p = getAccount(id);
if(p == NULL)
return;
cout << p->getAccountId() << "\t"
<< p->getAccountName() << "\t"
<< p->getBalance() << "\t"
<< endl;
}
bool Bank::draw(char* id,double amt)
{
Account *p = getAccount(id);
if(p == NULL)
return false;
if(!p->draw(amt))
{
cout << "Balance shortage!" << endl;
return false;
}
return true;
}
bool Bank::deposit(char* id,double amt)
{
Account *p = getAccount(id);
if(p == NULL)
return false;
p->deposit(amt);
return true;
}
bool Bank::transfer(char* srcId,char* dstId,double amt)
{
Account *pS = getAccount(srcId);
Account *pD = getAccount(dstId);
if(pS == NULL || pD == NULL)
{
cout << "Account is not existed!" << endl;
return false;
}
if(!pS->draw(amt))
return false;
pD->deposit(amt);
return true;
}
Account *Bank::getAccount(char* id)
{
for(vector<Account>::iterator
i = accounts.begin();
i != accounts.end();
i++)
{
if(!strcmp((*i).getAccountId(),id))
return &(*i);
}
return NULL;
}