C++ program with class Account

need help passing info from a user to my class

Page 1 of 1

3 Replies - 19385 Views - Last Post: 05 February 2010 - 07:20 PM Rate Topic: -----

#1 Ironsheik1089  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 17-June 09

C++ program with class Account

Posted 05 February 2010 - 11:56 AM

I am writing a C++ program with class Account. It will take an initial balance from a user and validate it through the constructor. Then through my member functions, modify the balance with another amount entered by the user and return the new balance.
please check out the code I have so far, I am not sure how far I am off to having a working program, thanks

// Account class definition

#include <iostream>
#include <string>
#include "Account.h"
using namespace std;

class Account
{
public:
        int initialBalance;
        
        Account::Account(int balance) //constructor to receive initial balance
        {   
            setInitialBalance(balance); //validate and store initial balance
        }

        //validates that the initial balance is greater than 0 dollars
        void Account::setInitialBalance(int balance)          
        {
            if(balance >= 0)
            {
                initialBalance = balance;  
            }
            else if(balance < 0)
            {
                initialBalance = 0;
                cout << "error, initial balance invalid!" << endl;
            }
        }
        
        int Account::credit(int) //adds an amount to the initial balance
        {
            
        }

        int Account::debit(int) //subtracts money from the initial balance
        {
            
            cout << "debit amount exceeded account balance." << endl;
        }

        int Account::getBalance(int) //returns the current account balance
        {
            return balance;
        }
}; // end class Account


#include <iostream>
#include <string>
#include "Account.h"
using namespace std;

int main()
{
    int balance;

    cout << "Enter your bank account balance: ";
    cin >> balance;

    // create two Account objects
    Account balance;
    Account amount(transaction);

    cout << "the balance is: " << balance.getBalance() << endl;
    return 0;
}



Is This A Good Question/Topic? 0
  • +

Replies To: C++ program with class Account

#2 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 387
  • View blog
  • Posts: 1,663
  • Joined: 16-May 09

Re: C++ program with class Account

Posted 05 February 2010 - 12:05 PM

When you are defining inline member functions, you don't have to write "Account::". Like this:
// Account class definition

#include <iostream>
#include <string>
#include "Account.h"
using namespace std;

class Account
{
        int initialBalance;
public:
        
        Account() {} //default constructor

        Account(int balance) //constructor to receive initial balance
        {   
            setInitialBalance(balance); //validate and store initial balance
        }

        //validates that the initial balance is greater than 0 dollars
        void setInitialBalance(int balance)
        {
            if(balance >= 0)
            {
                initialBalance = balance;  
            }
            else //if(balance < 0) you don't need this if, else will do the job
            {
                initialBalance = 0;
                cout << "error, initial balance invalid!" << endl;
            }
        }
        
        int credit(int) //adds an amount to the initial balance
        {
            
        }

        int debit(int) //subtracts money from the initial balance
        {
            
            cout << "debit amount exceeded account balance." << endl;
        }

        int getBalance() //returns the current account balance
        {
            return initialBalance;
        }
}; // end class Account

int main()
{
    int b; //you had an int and an Account variable with the same name!

    cout << "Enter your bank account balance: ";
    cin >> b;

    // create two Account objects
    Account balance; //gives error without a default constructor
    //Account amount(transaction); Wrong! where did you define transaction ?!
    balance.setInitialBalance(b); //or you could just have Account balance(b)

    cout << "the balance is: " << balance.getBalance() << endl;
    return 0;
}

Complete the remaining functions in your class. Note that compiler only creates a default constructor if you define no constructors for your class. Else, you have to define it yourself if you need it.

This post has been edited by Anarion: 05 February 2010 - 12:10 PM

Was This Post Helpful? 0
  • +
  • -

#3 Martyn.Rae  Icon User is offline

  • The programming dinosaur
  • member icon

Reputation: 545
  • View blog
  • Posts: 1,420
  • Joined: 22-August 09

Re: C++ program with class Account

Posted 05 February 2010 - 12:31 PM

You have a bit of a problem with this code, as I assume that there are two files in the post

//=========== if this is an include file, then the #include <iostream>, #include <string> ===========
//=========== #include "Account.h" and using namespace std; lines are spurious            ===========

// Account class definition

#include <iostream>
#include <string>
#include "Account.h"
using namespace std;

class Account
{
public:
        int initialBalance;
        
        Account::Account(int balance) //constructor to receive initial balance
        {   
            setInitialBalance(balance); //validate and store initial balance
        }

        //validates that the initial balance is greater than 0 dollars
        void Account::setInitialBalance(int balance)          
        {
            if(balance >= 0)
            {
                initialBalance = balance;  
            }
            else if(balance < 0)
            {
                initialBalance = 0;
                cout << "error, initial balance invalid!" << endl;
            }
        }
        
        int Account::credit(int) //adds an amount to the initial balance
        {
            
        }

        int Account::debit(int) //subtracts money from the initial balance
        {
            
            cout << "debit amount exceeded account balance." << endl;
        }

        int Account::getBalance(int) //returns the current account balance
        {
            return balance;          // <---- Where does this come from
        }
}; // end class Account


#include <iostream>
#include <string>
#include "Account.h"
using namespace std;

int main()
{
    int balance;

    cout << "Enter your bank account balance: ";
    cin >> balance;

    // create two Account objects
    Account balance;                 // <---- This is a problem because Account reqires a parameter
                                     //       for it's constructor. Use e.g. Account balance(0); 
     Account amount(transaction);    // <---- Where does this come from

    cout << "the balance is: " << balance.getBalance() << endl;
    return 0;
}


Was This Post Helpful? 0
  • +
  • -

#4 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 298
  • View blog
  • Posts: 1,839
  • Joined: 20-September 08

Re: C++ program with class Account

Posted 05 February 2010 - 07:20 PM

You might like to try something like this:

// classAccount.cpp


// #include "Account.h" // handles dollars and cents as an integer all in cents

// account.h

#ifndef _ACCOUNT_H_
#define _ACCOUNT_H_

#include <iostream>
#include <sstream>
#include <string>


const std::string $$$ = "CAD"; // if account in Canadian dollars

class Account
{
public:

    // default constructor ... with opening balance 0
    Account() : balance( 0 )
    { std::cout << "Your opening balance is: "; printBalance(); }

    // constructor to receive and validate/adjust initial balance to >= 0
    Account( int bal ) : balance( bal )
    {
        setInitialBalance();
        std::cout << "Your opening balance is: ";
        printBalance();
    }

    // adds (validated?) amount to the balance
    void credit( int amount )
    {
        //
    }

    // subtracts (validated?) amount from the balance
    void debit( int amount )
    {
        if( amount <= balance ) balance -= amount;
        else std::cout << "Debit requested of " << centsToDolsStr( amount )
                       << " exceeded account balance of "
                       << centsToDolsStr( balance ) << std::endl;
        std::cout << "After debit request of " << centsToDolsStr( amount )
                  << " the balance is: " << centsToDolsStr( balance )
                  << std::endl;
    }
    
    void printBalance()
    {
        std::cout << centsToDolsStr( balance ) << std::endl;
    }
    
    // returns the current balance of the account
    int getBalance() {  return balance; }
    
private:
    int balance;
    
    // validates/adjusts ... that the initial balance is >= 0 dollars ... But
    // note how the main program here supplies validated data to class Account
    void setInitialBalance()
    {
        if( balance < 0 )
        {
            std::cout << "\nError! Initial balance set to zero ...\n"
                      << "(since invalid negative opening balance requested.)\n"
                      << std::endl;
            balance = 0;
        };
    }
    
    std::string centsToDolsStr( int all_cents )
    {
        std::ostringstream oss;
        oss << all_cents / 100 << '.';
        int cents = all_cents % 100;
        if( cents > 9 ) oss << cents;
        else oss << 0 << cents;
        oss << " " << $$$;
        return oss.str();
    }
    
}; // end class Account

#endif


// utility function used by main ...

// defaults to No ...
bool ok() 
{
    std::cout << "Ok ... y/n ? " << std::flush;
    int reply = std::cin.get();
    std::cin.sync();
    return reply == 'y' || reply == 'Y';
}

bool isValid( const std::string& strToTest )
{
    if( strToTest == "" ) return false;
    int len = strToTest.length();
    if( len < 4 ) { std::cout << "Must be at least 0.00 entered ...\n"; return false; }
    if( len > 10 ) { std::cout << "Max entry is 9999999.99\n"; return false; }
    if( strToTest[len-3] != '.' ) return false;
    // Note: if reach here ... len >= 4
    for( int i = 0; i < len; ++i )
    {
        if( i == len-3 ) ++i; // skip over '.' ...
        if( strToTest[i] < '0' || strToTest[i] > '9' ) return false;
    }
    // if reach here ...
    return true;
}

int dolsStrToCents( const std::string& dolsStr )
{
    std::istringstream iss( dolsStr );
    int dols, cents;
    char dummy;
    iss >> dols >> dummy >> cents;
    return dols*100 + cents;
}

int getValidDolsAndCents( const std::string& prompt )
{
    std::string dolsStr;
    for( ; ; ) // forever loop ...
    {
        std::cout << prompt << std::flush;
        getline( std::cin, dolsStr );
        if( isValid( dolsStr ) )
            return dolsStrToCents( dolsStr );
        // else if reach here ...
        std::cout << "Valid format for input here is 1.23 ...\n";
    }
}


int main()
{
    // create new account object myAccount with validated opening balance ...
    std::string prompt_message = "Enter your opening balance like this 23.00 : ";
    Account myAccount( getValidDolsAndCents( prompt_message ) );

    //std::cout << "Your opening balance is: ";
    //myAccount.printBalance();
    
    std::cout << std::endl;
    
    prompt_message = "Enter the amount to withdraw like this 20.00 : ";
    myAccount.debit( getValidDolsAndCents( prompt_message ) );
    
    std::cout << "\nPress 'Enter' to continue ... " << std::flush;
    std::cin.get();
}



You might note that since the data is validated at input, the validation inside the class is redundant.

This post has been edited by David W: 05 February 2010 - 07:23 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1