#include <ios>
#include <iostream>
#include <iomanip>
#include <limits>
#include <stdexcept>
#include <string>
class Account {
std::string _name;
// Represented by the number of pennies, so on a
// 32-bit system these accounts are limited to
// $42,949,672.96. Beware arithmetic overflow
unsigned long _balance;
public:
Account(): _balance ( 0 ) {}
Account ( std::string name, unsigned long initial_balance )
: _name ( name ), _balance ( initial_balance )
{}
std::string Name() const
{
return _name;
}
unsigned long Balance() const
{
return _balance;
}
unsigned long Credit ( unsigned long amount )
{
return _balance += amount;
}
unsigned long Debit ( unsigned long amount )
{
if ( amount > _balance ) {
throw std::runtime_error (
"Cannot debit more than the account contains" );
}
return _balance -= amount;
}
friend std::ostream& operator<< ( std::ostream& out, const Account& acct )
{
return out<< acct._name <<": "<< acct._balance / 100 <<"."
<< std::setfill ( '0' ) << std::setw ( 2 ) << acct._balance % 100;
}
};
int main()
{
Account accts[10];
int n = 0;
while ( true ) {
std::cout<<"> ";
std::string command;
if ( !getline ( std::cin, command ) || command == "q" )
break;
if ( command == "new" ) {
std::string name;
unsigned long balance;
std::cout<<"Name: ";
getline ( std::cin, name );
std::cout<<"Balance: ";
std::cin>> balance;
std::cin.ignore();
accts[n++] = Account ( name, balance );
}
else if ( command == "credit" ) {
std::string name;
unsigned long amount;
std::cout<<"Account name: ";
getline ( std::cin, name );
std::cout<<"Amount to debit: ";
std::cin>> amount;
std::cin.ignore();
for ( int i = 0; i < n; i++ ) {
if ( accts[i].Name() == name ) {
try {
accts[i].Debit ( amount );
} catch ( std::exception& ex ) {
std::cout<< ex.what() <<'\n';
}
}
}
}
else if ( command == "debit" ) {
std::string name;
unsigned long amount;
std::cout<<"Account name: ";
getline ( std::cin, name );
std::cout<<"Amount to credit: ";
std::cin>> amount;
std::cin.ignore();
for ( int i = 0; i < n; i++ ) {
if ( accts[i].Name() == name )
accts[i].Credit ( amount );
}
}
else if ( command == "report" ) {
for ( int i = 0; i < n; i++ )
std::cout<< accts[i] <<'\n';
}
else
std::cout<<"Unrecognized command\n";
}
}