Hi there, it's been awhile :$
I have just completed a small easy exercise which was to create an Account class, providing a constructor to receive the initial account balance, add some money to the initial balance and withdraw some money (providing that the amount of money to withdraw is smaller than the value in the account) It's all good but now I am having some problems in validating the input. Basically when asked to add some money onto the account if I input a char I want my program to tell me that the input is invalid and to try again, but I don't seem to be able to do it. Here is what I have so far:
header file:
//account.h
//this file is the class definition
#include <iostream>
using namespace std ;
const char pound = 156 ;
class Account
{
public:
//constructor
Account( int ) ;
void credit( int ) ;
void debit( int ) ;
int getBalance( ) ;
private:
int balance ;
};
function definition:
//account.cpp
//this file contains the member function definitions
#include <iostream>
using namespace std ;
#include "account.h" //include the class definition
Account::Account( int initBalance )
{
if ( initBalance < 0 )
{
balance = 0 ;
cout << "Initial balance is invalid!\n" ;
}
else
{
balance = initBalance ;
cout << "The initial balance is "<< pound << balance << endl ;
}
}
void Account::credit( int funds )
{
balance += funds ;
}
void Account::debit( int withdraw )
{
if ( withdraw > balance )
{
cout << "Debit amount exceeded Account's balance!\n" ;
}
else
{
balance -= withdraw ;
}
}
int Account::getBalance()
{
return balance;
}
main file: this is where I am attempting the validation as the comment says
//account_main.cpp
//main file
#include <iostream>
#include <cctype>
using namespace std ;
#include "account.h"
int main()
{
int addBalance ; //to pass the fund
int toDebit ; //to pass the withdraw
Account money(300) ;
cout << " You can now add some fund to your account. How much do you want to add?\n" ;
cin >> addBalance ;
/*this is where I try to validate the input but the compiler, if I enter a char or even a 3 digits number comes back with an error (I attached the screenshot)*/
if ( isalpha( addBalance ) )
{
cout << " Not a valid input, try again!\n " ;
cin >> addBalance ;
}
cin.ignore() ;
money.credit( addBalance ) ;
cout << "The new balance after the deposit is " << pound << money.getBalance() << endl ;
cout << "Now you can withdraw money. How much would you like to withdraw?\n" ;
cin >> toDebit ;
cin.ignore() ;
money.debit( toDebit ) ;
cout << "The new balance after the withdraw is " << pound << money.getBalance() << endl ;
return 0;
}
I attached the error the compiler gives me
thanks