C++ Values not been stored as needed - c++

This code is from my "virtual ATM machine" program which deals with customers depositing, checking balance and withdrawing money from their account. When I deposit the money, it displays that it gets deposited.. But... here goes the code before I state my problem:
double bankAccount::deposit()
{
bankAccount b;
double amt;
system("cls");
cout << " ----------------------------------------------------------------------- \n";
cout << "| Customer Menu | \n";
cout << " ----------------- ----------------- ----------------- ----------------- \n";
cout << "\n\nYOUR CURRENT BALANCE: " << balance << endl;
cout << "\nEnter amount to deposit: ";
cin >> amt;
balance = (balance + amt);
cout << "\nAmount depositted successfully!" << endl;
cout <<"\nYOUR CURRENT BALANCE: " << balance;
getch();
customer_actions();
return balance;
}
"customer_actions()" being the main menu for the customers, when I go back on that screen and select the option to check balance, it displays as ZERO. Which means the values didn't get updated from the previous function. Here's my header file which consists of the class file:
#ifndef bank
#define bank
using namespace std;
class bankAccount
{
public:
int accNo;
int password;
double balance;
double withdrawamt;
double depositamt;
char name[20];
char address[40];
char username[10];
public:
double checkbalance();
double deposit();
double withdraw();
public:
bankAccount()
{
balance = 0; // Is this the reason?
}
};
#endif
I'm thinking, when the program switches from one menu to the other, the values get reset-ed. Any suggestions, dear folks?
Thanks in advance!
CUSTOMER_ACTIONS:
int customer_actions()
{
bankAccount b;
int cust_selection;
system("cls");
cout << " ----------------------------------------------------------------------- \n";
cout << "| Customer Menu | \n";
cout << " ----------------- ----------------- ----------------- ----------------- \n";
cout << " Please Select option to continue: \n" << endl << endl;
cout << "1) Check balance : Press 1" << endl;
cout << "2) Withdraw Cash : Press 2" << endl;
cout << "3) Deposit Cash : Press 3" << endl;
cout << "4) Transfer Cash : Press 4" << endl;
cout << "5) Return home : Press 5" << endl;
cout << "\nEnter option: ";
cin >> cust_selection;
switch(cust_selection)
{
case 1: b.checkbalance(); break;
case 2: b.withdraw(); break;
case 3: b.deposit(); break;
case 4: break;
case 5: main(); break;
}
}

Your problem (from what I can see) is that you are trying to create an infinite loop where the user can keep pressing making changes on the menu until they exit. However you are going about this by calling customer_actions() from within the deposit function.
Try creating an infinite loop in an outer method, then returning from deposit without calling customer_actions().
Following OP edit
Try this:
int main(...)
{
int result = 0;
while(result == 0)
{
result = customer_actions();
}
}
Now change the switch statement in customer_actions to be like this:
switch(cust_selection)
{
case 1: b.checkbalance(); break;
case 2: b.withdraw(); break;
case 3: b.deposit(); break;
case 4: break;
case 5: return 1; // This is the change
}
return 0;

The bank account b you declare in customer_action is just valid in function scope.
In addition:
customer_action manages given accounts by their interface, accounts should not "manage" customer_action (in your case, don't call it from deposit)
You could easily get a stack overflow the way you coded that.
Generally speaking you should try to avoid mixing up model (your accounts) view (the output) and controller (user input) - related code.
Create clean interfaces and call in in a structured manner.
In addition:
I first read your bold put question and afterwards attended the code.
The first thing I did then was was trying to find if there is local redefinition of double balance. There is none, but I should not even have had to do so, because there are means to avoid side-effects on instance member variables like balance.
Foremost - make them private, not public.
Then:
use a prefix like m_ so m_balance that would be or even m_dblBalance to indicate the type
or prefix all private variables with a _, so _balance that would be
and/or emphasize each usage of instance member vars by prefixing them with a redundant this->
Personally speaking I dislike 1. but use 2. for instance variables.
There are many more design and implementation issues, eg. I would discourage char[] for strings and recommend using std::string, but maybe you start by just ending the marriage of deposit() and customer_actions() you blessed.

Related

C++ Phone Book - User Input Into Arrays

I'm very new at C++ and I am having trouble with my phone book program.
The issue is when I go to add a contact, it saves the name and number in the arrays. If I choose switch case 2 after adding each contact, it'll list all the contacts and phone numbers normally. But if I select switch case 1 multiple times in a row and add more than one contact before I select switch case 2 to display all the contacts, it will only print the most recent contact I added.
The code is unfinished, but I can't seem to figure this one out! When I add more than one contact at a time, does it override the most recent one I just added? Sorry if I am not explaining this well, I'm not yet familiar with all the proper terminology!
I also don't want to use a loop for the input, so the user will not have to input ten names and numbers all at once if they don't want to. Unless there's a way to use a loop and have them end it after a certain amount of entries.
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
using namespace std;
string nameArray[10];
string numberArray[10];
int arraySize = 10;
int index;
int i;
void addContact() {
// Get user input
cout << "\n\tEnter contact information" << endl;
cout << "\t==========================" << endl;
cout << "\tEnter name: ";
getline(cin, nameArray[i]);
cout << "\tEnter phone number: ";
cin >> numberArray[i];
cin.ignore();
}
void viewAll() {
// Declare variables
int pass = -1;
string tempNumber = "";
string tempName = "";
// Sort array in ascending order
for(pass=0; pass<9; pass++) {
for(index = 0; index < (9 - pass); index++) {
if(nameArray[index] > nameArray[index + 1]) {
tempName = nameArray[index];
nameArray[index] = nameArray[index + 1];
nameArray[index + 1] = tempName;
tempNumber = numberArray[index];
numberArray[index] = numberArray[index + 1];
numberArray[index + 1] = tempNumber;
}
}
}
// Print contacts after sort
cout << endl;
for(int j=0; j<arraySize; j++) {
cout << '\t' << nameArray[j] << '\t' << '\t' << numberArray[j] << endl;
}
}
void searchContact() {
}
void editContact() {
}
void deleteContact() {
}
int main() {
int choice;
while(1) {
cout << "\n\t\tMAIN MENU" << endl;
cout << "\t=======================" << endl;
cout << "\t [1] Add Contact" << endl;
cout << "\t [2] View All Contacts" << endl;
cout << "\t [3] Search Contact" << endl;
cout << "\t [4] Edit Contact" << endl;
cout << "\t [5] Delete Contact" << endl;
cout << "\t [6] Exit Program" << endl;
cout << "\t=======================" << endl;
cout << '\t';
cin >> choice;
switch(choice) {
case 1: // Add a new contact
cin.ignore();
addContact();
break;
case 2: // Print all contacts in alphabetical order
viewAll();
break;
case 3: // Search and print contact name and phone number
searchContact();
break;
case 4: // Edit a contact
editContact();
break;
case 5: // Delete a contact
deleteContact();
break;
case 6: // End program
return 0;
break;
default:
cout << "\nInvalid choice." << endl;
break;
}
}
return 0;
}
i think Johnny Mopp has given you the correct answer, but you said your new so i'd like to give you a slightly longer explanation, and a little bonus advice.
Consider your addContact function. You ask for values to be inserted into the name and numbers array at position i. You need to update that position after you add a contact or it will simply overwrite what was there previously. So a ++i; at the end of the function will solve your problem as this means next time you add a contact it goes to the next slot in the array. Now be mindful of this as your array only has (right now) 10 items in it, so once you add 10 entries i will have a value of 10 now which if you try to do nameArray[i] it would be trying to access, or worse write to, the 11th item in your array which does not exist, this is very bad (take a quick google tour of "buffer overflow error"). So make sure you add a safety check in at the start of addContact that checks if i == 10 in which case you could for example: print an error message then return from the function immediately. Definately DO NOT try to access an element of the array that does not exist.
I would also recommend explicitly initialising i to 0 just for clarity (it will be 0 because it is a global variable, but it would not be 0 if it was declared inside a function, so its a good habit to get into)
Finally, you seem to be using a mix of declaring a loop variable outside of the loop for(pass=0;...) and declaring it inside the loop for(int y = 0;...) from what i can see you dont use the variables declared outside of the loop like pass or index for anything except looping, so consider declaring them in the loop where they are used, this just keeps things a bit tidier and avoids mistakes where because the variable is still in scope someone might think its valid to use it as an array index or the likes.
Hope thats useful.

Restaurant Billing Program Function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to make a restaurant bill calculator program that allows people to choose from a list of menu items (a function) until they have everything they've wanted to order and then calculate the total when they are finished selecting from a list. Then it takes the amount they tender and subtracts the total plus tax and tip to calculate change.
I've found several ideas and similar programs here and on other places but nothing that has given me a good enough idea of how to get this finalized. I have the program coded but I can't figure out how to take the running total and keep accumulating it until the user enters "8". I have a functioning program but it totals after each selection instead of keeping a running total and calcuating it when the user hits the "8" key to end.
Take a look below and see if you can point my in the right direction if you would. Basically this assignment is about functions so we're asked to use functions to display the menu and calculate the total.
#include <iostream>
#include <iomanip>
using namespace std;
// Function Prototypes
void showMenu();
void showFees(double, int);
int main()
{
int choice; //To Hold Menu Choice
double quantity = 1;
//contants for menu choices
const int hamburgerChoice = 1;
const int hotdogChoice = 2;
const int peanutsChoice = 3;
const int popcornChoice = 4;
const int sodaChoice = 5;
const int chipsChoice = 6;
const int waterChoice = 7;
const int endOrderChoice = 8;
//constants for menu prices
const double hamburger = 6.00;
const double hotdog = 4.50;
const double peanuts = 3.75;
const double popcorn = 5.50;
const double soda = 2.80;
const double chips = 1.00;
const double water = 2.00;
//set precision
cout << fixed << showpoint << setprecision(2);
do
{
//display menu and get user choice
showMenu();
cin >> choice;
//validate choice
while (choice < hamburgerChoice || choice > endOrderChoice)
{
cout << "Please enter a valid menu choice: ";
cin >> choice;
}
//if the user does not want to quit proceed
if (choice != endOrderChoice)
{
//display fees
switch (choice)
{
case hamburgerChoice:
showFees(hamburger, quantity);
break;
case hotdogChoice:
showFees(hotdog, quantity);
break;
case peanutsChoice:
showFees(peanuts, quantity);
break;
case popcornChoice:
showFees(popcorn, quantity);
break;
case sodaChoice:
showFees(soda, quantity);
break;
case chipsChoice:
showFees(chips, quantity);
break;
case waterChoice:
showFees(water, quantity);
break;
}
}
}
while (choice != endOrderChoice);
system("pause");
return 0;
}
//*************************************************************
//Definition of function showMenu which displays the menu **
//*************************************************************
void showMenu()
{
cout << "\n\t\tBaseball Game Snacks" << endl;
cout << "1. Hamburger \t$6.00"<< endl;
cout << "2. Hotdog \t\t$4.50" << endl;
cout << "3. Peanuts \t\t$3.75" << endl;
cout << "4. Popcorn \t\t$5.50" << endl;
cout << "5. Soda \t\t$2.80" << endl;
cout << "6. Chips \t\t$1.00"<< endl;
cout << "7. Water \t\t$2.00" << endl;
cout << "8. END ORDER" << endl;
cout << "Please enter your menu choice: ";
}
//************************************************************
//Definition of function showFees which caculates the total **
//bill **
//************************************************************
void showFees(double itemCost, int quantity)
{
double amtTendered;
double totalBill = (itemCost * quantity);
double taxRate = .065;
double tipRate = .20;
double tip = (totalBill * tipRate);
double tax = (totalBill * taxRate);
double amountDue = (totalBill + tax + tip);
cout << "Total Bill: $" << totalBill << endl;
cout << "Tax: $" << tax << endl;
cout << "Tip: $" << tip << endl;
cout << "Total Amount Due: $" << amountDue << endl;
cout << "Enter ammount tendered: $";
cin >> amtTendered;
double changeDue = amtTendered - amountDue;
cout << "Change Due: $" << changeDue << endl;
}
The "balance" is calculated by the showFees function. So, your problem is that you need to maintain the state (some data) in showFees in subsequent calls. The best way you could do this is using OOP. While you are programming in C++ using the procedural paradigm, I will point you some of the solutions available in procedural programming.
Global variables
You could have a global variable to hold the total. This is the simplest, the most intuitive and the worst solution you could have. Don't.
Static variables
You could have a static variable in showFees that stores the current total. Better than a global variable, but still bad.
Store the total in main
Create a variable that represents the total, initialize it to 0 and create a third argument of showFees that takes a pointer to a double. This way, the changes done to that variable will remain after the showFees function call ends. In C++ you can use references also (this is the recommended way in C++).
Improve your program
In programming there is a concept called modularity. Using functions, you don't have duplicate code. But a function should do only one thing, and do it as best as possible. This way, your functions are smaller and easier to manage. In showFees you do 2 things: compute some financial things and generate output. This should always be separated. The computations, or business logic, should be done in a function (that can work in the way I described above), and the output generation, or visual logic, in another function.
Of course, this is a small program and the separation that I talk about is probably an overkill. However, you can think at ways to improve your function so that they are as modular as possible.

infinite loop while there is a cin function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
so i am working on an a little project the main idea of is that there library that have library items(book,magazine) and student and the main menu of the program have adding student,library item removing student library items...etc,so when i am trying to add a book it work perfect but when i am trying to add magazine it get into a infinite loop and doesn't letting me to enter value to enter other option and its my first program i may have a-lot of error using dev c++ and it not done yet the code::
#include<iostream>
#include<string>
using namespace std;
char enter;
string none,none1,none2;
int is,iff;
int B_num=0;//books number
int M_num=0;//magazine number
int S_num=0;//student number
class Clibrary_items{//the clibrary class is a class that got the common elemt of the magazine and the book
protected:
string name,publisher;
string av="availabil";//the availability of a book or a magazine
};
class Cbook: public Clibrary_items{
private:
string author_name;
public:
virtual void set(string n,string p,string a)
{
name=n;
publisher=p;
author_name=a;
}
virtual void print()//the the printer function that print the pointed book
{
cout<<"the name is::"<<name<<endl;
cout<<"the publisher is::"<<publisher<<endl;
cout<<"the author name is::"<<author_name<<endl;
}
};
class Cmagazine: public Clibrary_items{
private:
int isbn;
public:
virtual void set(string na,string pu,int i)
{
name=na;
publisher=pu;
isbn=i;
}
virtual void print()//the the printer function that print the pointed magazine
{
cout<<"the name is::"<<name<<endl;
cout<<"the publisher is::"<<publisher<<endl;
cout<<"the issue number is::"<<isbn<<endl;
}
};
class Cstudent{
friend class Clibrary;
private:
string name="";
int ID;
public:
void set(string sn,int number)
{ID=number;
name=sn;}
void print_student()//the the printer function that print the pointed student
{ cout<<"ID:"<<ID<<" ";
cout<<"student name is::"<<name<<endl;}
};
class Clibrary//the main class
{
public:
Cbook book[100];//dynamic array for books
Cmagazine magazine[100];//dynamic array for magazine
Cstudent student[100];//dynamic array for student
void print()//the main function that print the main menu and get you to everthing
{
while(enter!='q')
{
cout << "[a] Add student" << endl;
cout << "[b] Remove student" << endl;
cout << "[c] Add Item to the Library" << endl;
cout << "[d] Remove Item from the Library" << endl;
cout << "[e] Borrow Item from the Library" << endl;
cout << "[f] Return Item to the Library" << endl;
cout << "[g] Show all Library Items" << endl;
cout << "[i] Show all reserved Library items" << endl;
cout << "[j] Show all free Library items" << endl;
cout << "[k] Show all students" << endl;
cout << "[l] Show all students who borrowed items" << endl;
cout << "[m] Find the student who borrowed a specific item" << endl;
cout << "[n] Show all Items borrowed by student" << endl;
cout << "q) Quit to Windows" << endl;
cin>>enter;
switch (enter)
{
case 'a':
cout<<"please enter the name::";
cin>>none;
student[S_num].set(none,S_num);
S_num++;
break;
case 'k':
for(int i=0;i<S_num;i++)
{
student[i].print_student();
}
break;
case 'b':
cout<<"please enter the name of the student you want to remove:";
cin>>none;
for(int i=0;i<S_num;i++)
if(none==student[i].name)
student[i].name="";
break;
case 'c':
cout<<"[1].add book"<<endl;
cout<<"[2].add magazine"<<endl;
cin>>iff;
if(iff==1)
{
cout<<"please enter the name of the book:"<<endl;
cin>>none;
cout<<"please enter the publisher:"<<endl;
cin>>none1;
cout<<"please enter the author name:"<<endl;
cin>>none2;
book[B_num].set(none,none1,none2);
}
if(iff==2)
{
cout<<"please enter the name of the magazine:"<<endl;
cin>>none;
cout<<"please enter the publisher:"<<endl;
cin>>none1;
cout<<"please enter the issue number:"<<endl;
cin>>is;
magazine[M_num].set(none,none1,is);
}
break;
}
}
}
};
main()
{
cout <<"****** ****** ****** ****** ****** ******" << endl;
cout <<"* *" << endl;
cout <<"****** Library Management System ******" << endl;
cout <<"* *" << endl;
cout <<"* BY: <M.Saed Ramadan> *" << endl;
cout <<"* *" << endl;
cout <<"****** ****** ****** ****** ****** ******" << endl;
Clibrary librarby;
librarby.print();
}
To make your code more manageable, I suggest you use function calls in your switch statement:
switch (selection) // "enter" is such a bad name.
{
case 'a':
Add_Student();
break;
case 'b':
Remove_Student();
//...
default:
cout << "Invalid menu selection, try again.\n";
break;
}
This simplification (for easy reading) leads to the following table driven menu system:
// Declare a function pointer syntax
typedef void (*Function_Pointer)(void);
struct Menu_Entry
{
char selection_char;
Function_Pointer menu_function;
};
// The table
const Menu_Entry First_Menu[] =
{
{'a', Add_Student}, // A selection entry
{'b', Remove_Student},
//...
};
const unsigned int Number_Of_Selections =
sizeof(First_Menu) / sizeof(First_Menu[0]);
// The lookup engine
char selection; // This you input from user.
for (unsigned int i = 0; i < Number_Of_Selections; ++i)
{
if (selection == First_Menu[i].selection_char)
{
// Execute the function associated with the selection
First_Menu[i].menu_function();
break;
}
}
An advantage to the table system is that you can easily add a menu selection item by:
Creating a function to perform the selection.
Adding a Menu_Item entry to the table.
That's it. Quite simple.
Which allows you to get the menu selection process working for one selection, then work on another; piece by piece.
By placing the functions in separate files, you only need to compile the lookup table source and the new selection source files. All the other code remains untouched. Much faster build times.

C++ basic menu driven program (calling functions)

I'm new to programming and am trying to figure out why this is happening.
Basically I'm asked to design a menu driven program that does some basic deposit/withdrawal calculations. I'm supposed to write different functions for each process and call on them when necessary.
I'm having 2 problems:
1) My functions aren't updating my variables within the program. For example it will run, I can enter my starting balance, I can enter my transaction type and amount but every time I switch from deposit to writing a check, it resets the balance to the original user input.
2) When I want the program to exit, it is still asking me for the double input. Not sure how to make it accept just an "E" instead of "E number"
Thanks in advance.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//Prototypes for my functions that will be called in
void displayMenu();
double checkProcess(double, double);
double depositProcess(double, double);
double totalServCharge(double);
int main()
{
//Variables needed for the problem
char choice; //menu choice
double transAmt, balance, numbServCharge; //transaction amount, current balance, total service charges, number of service charges
numbServCharge = 0; //Start the counter for number of service charges at zero
cout << "Checkbook Program\n\n";
cout << "Enter the beginning balance: ";
cin >> balance; //get the initial balance
cout << endl;
do
{
//Call the display menu function
displayMenu();
//Get user's choice and transaction amount from menu
cout << "Enter a transaction: ";
cin >> choice >> transAmt;
choice = toupper(choice);
cout << endl;
//Create an error message for invalid choice and get a second choice
while((choice != 'C') && (choice != 'D') && (choice != 'E'))
{
cout << "Invalid selection. Please choose C, D or E: ";
cin >> choice;
}
//Set up for option #1 -- using a check
if(choice=='C')
{
//Call check function and service charges function
checkProcess(transAmt, balance);
totalServCharge(numbServCharge);
}
//Set up for option #2 -- deposits
if(choice=='D')
{
//Call deposit function and service charges function
depositProcess(transAmt, balance);
totalServCharge(numbServCharge);
}
}while(choice != 'E'); //Close program if option 3 is selected
//Display final balance
cout << "Processing end of the month";
cout << "\nFinal balance : $ " << fixed << setprecision(2) << balance << endl << endl;
system("pause"); //Pause screen so it doesn't close right away
return 0;
}
void displayMenu()
{
//Highlight menu options
cout << "\nCommands\n";
cout << "C amount - process a check in a specific amount\n";
cout << "D amount - process a deposit in a specific amount\n";
cout << "E - end the program\n\n";
}
double checkProcess(double transAmt, double balance)
{
cout << "\nProcessing check for $" << fixed << setprecision(2) << transAmt;
transAmt = transAmt + .25; //Add the service charge onto the transaction
balance = balance - transAmt; //Update account balence
cout << "\nBalance: $" << fixed << setprecision(2) << balance;
cout << "\nService charge: $0.25 for a check\n";
return balance;
}
double depositProcess(double transAmt, double balance)
{
cout << "\nProcessing Deposit for $" << fixed << setprecision(2) << transAmt << endl;
transAmt = transAmt - 0.25; //Add the service charge onto the deposit
balance = balance + transAmt; //Update account balence
cout << "Balance: $" << fixed << setprecision(2) << balance << endl;
return balance;
}
double totalServCharge(double numbServCharge)
{
double totalServCharge = 0;
numbServCharge++; //Add one to the number of service charges there have been
totalServCharge = .25 * numbServCharge; //Update total cost of service charges
cout << "Total service charges: $" << fixed << setprecision(2) << totalServCharge << endl; //Tell user total service charges so far
return numbServCharge;
}
(1) Your variables aren't updating because you aren't changing them; you're changing the copies passed to your subroutines. You either need to pass the current balance by reference (so that when you change it in the subroutine scope, you're also changing the original) or assign the return value from your subroutines to your current balance.
When you pass a variable by value (as you are now), the program makes a copy of that variable for use in the function scope. When you leave that scope, the copy is deleted. Do this when you want to be sure a subroutine won't alter anything in the scope from which it is called. If you want the subroutine to alter the variables you pass to it, pass the variables by reference. In this function signature, "transAmt" is passed by value and "balance" is passed by reference:
double foo(double transAmt, double& balance);
Incidentally, if you pass the balance by reference there's no reason to return it. You aren't doing anything with the returned value right now anyway.
(2) If you want to not ask for a number when "E" is given, make separate "cin" statements for the number in the conditional blocks for "C" and "D". Right now all your input code is shared between all cases. It would be even better if you arrange things so that you exit the loop before a number is asked for. This way, you only have to write that "cin" statement once.
It's becouse in C++ when you call a function with parameter, you only operate on COPIES of those parameters. If you want to change the original value, pass variable as reference.
See those simple examples:
#include <iostream>
using namespace std;
void normal(int a)
{
a += 10;
}
void by_reference(int &a) //Notice ampersand
{
a += 10;
}
int by_return(int a)
{
return a + 10;
}
int main()
{
int a = 5;
cout << "Start: " << a <<endl;
normal(a);
cout << "Normal: " << a <<endl;
by_reference(a);
cout << "Reference: " << a <<endl;
a = by_return(a);
cout << "Return: " << a <<endl;
}
Now you can see that if you pass the variable as reference it gets changed.
Even if just putting the & before parameter names would fix your problem, I'd recommend you using a return, it generally is simplier and makes your code look better (it's much easier to understand).
Also, correct your indentation. It's very bery important when you work with bigger projects.
Hope this helps. :)
1 | The first problem is occurring because you are not actually modifying the user's input. You are passing the variable in but once the new value is returned you are not storing it, thus the value is forgotten in the main function. Not the best solution, but it might suit you to do this:
if (choice == 'D')
{
//Call deposit function and service charges function
balance = depositProcess(transAmt, balance); // Overwrite balance
numbServCharge = totalServCharge(numbServCharge); // Overwrite numbServCharge
}
Or in a more efficient way, you can pass in the variable by reference. All you would need to do is change the function prototype.
void totalServCharge(double&);
void depositProcess(double&, double&);
Now when the variable is passed in, it will be modified directly by the function. Also note the function data type changed to void because you no longer need to return a value from the function.
2 | Your second problem is the way you handle user input. If you want to ask for multiple input, it might sometimes be best to do it with separate cout and cin statements.
The way it is set in your program is for the user to enter two inputs at once, therefore if you only enter E, it waits patiently as it should for your next input (transAmt). It might be better to process the action desired and then have an amount entered afterwards.
Very general example:
do {
cout << "1 : Transaction or 2 : Exit" << endl;
cin >> choice;
if (choice == 2)
break;
cout << "1. Deposit\n" << "2. Check" << endl;
cout << "Enter transaction type followed by amount" << endl;
cin >> transType >> amount;
// Then do what was specified in choice
} while (true); // Or whatever condition pleases you

Object is initializing to unwanted value

I have been working on a trivial assignment to get used to coding. I am designing an ATM machine and at the moment it is composed of 2 classes:
BankAccount.cpp
Constructor for different types of account
Only has balance as a member
Transaction.cpp
Performs a method on the BankAccount (i.e make deposit, make withdrawl & get balance)
Problem: BankAccount is automatically initialized to a balance of 10 which is undesired. So for example, if I made a checking account and chose to deposit $10, balance would print out $20.
//BankAccount.h
//This class will simply take in a bank account
//with a balance, other classes will use a bank account object
//such as saving/checkings and perform operations on the
//balance
#ifndef BANK_ACCOUNT_H
#define BANK_ACCOUNT_H
class BankAccount {
private:
float balance;
public:
BankAccount ();
float getBalance ();
void makeDeposit ();
void makeWithdrawl ();
};
#endif
//BankAccount.cpp
#include "BankAccount.h"
#include <iostream> //remove once done *not to self
using namespace std; //remove once done *note to self
BankAccount::BankAccount() {
balance = 0.00;
}
float BankAccount::getBalance() {
return balance;
}
void BankAccount::makeDeposit() {
cout << "How much would you like to deposit: ";
float deposit_value;
cin >> deposit_value;
balance += deposit_value;
}
void BankAccount::makeWithdrawl() {
cout << "How much would you like to withdrawl: ";
float withdrawl_value;
cin >> withdrawl_value;
balance -= withdrawl_value;
}
//Transaction.h
#ifndef TRANSACTION_H
#define TRANSACTION_H
class Transaction {
private:
BankAccount m_bao;
public:
Transaction(BankAccount&);
void displayOptions();
void printReciept();
};
#endif
//Transaction.cpp
#include "BankAccount.h"
#include "Transaction.h"
#include <iostream>
using namespace std;
Transaction::Transaction(BankAccount& bao) {
m_bao = bao;
}
void Transaction::displayOptions() {
cout << "\nPlease make a choice\n\n";
cout << "1: Make Deposit\n";
cout << "2: Make Withdrawl\n";
cout << "3: Check Balance\n";
int choice;
cin >> choice;
switch (choice) {
case 1:
m_bao.makeDeposit();
break;
case 2:
m_bao.makeWithdrawl();
break;
case 3:
m_bao.getBalance();
break;
}
}
void Transaction::printReciept() {
cout << "Current balance is now: " << m_bao.getBalance() + '\n';
}
int main () {
BankAccount checking;
Transaction q(checking);
q.displayOptions();
q.printReciept();
}
I am sure the answer is right in front of my eyes, but my brain is just fried right now. I will continue to look for the solutions and let you guys know if my problem has been solved yet.
[EDIT]
Alright, now I am trying to make it so that the customer can choose to perform transactions on either Checking or Savings account. Currently I got it looking like this in my main():
int main () {
BankAccount checking(0.00);
BankAccount savings(0.00);
Transaction c(checking);
Transaction s(savings);
for(int i = 0; i < 10 ; i++) {
cout << "Make an option" << endl;
cout << "1. Checking " << endl;
cout << "2. Savings" << endl;
int choice;
cin >> choice;
if (choice == 1) {
c.prompt();
c.printReciept();
}
else {
s.prompt();
s.printReciept();
}
}
}
It works fine, but I would like to make this process more OOP-alized, if that makes sense :)
One option I was trying to look into was making a prompt function which would belong to Transaction.cpp. This would do everything that is done in main, except initializing the objects of course.
Your problem is this line:
cout << "Current balance is now: " << m_bao.getBalance() + '\n';
Which the compiler sees as:
cout << "Current balance is now: " << (m_bao.getBalance() + '\n');
'\n' is 10 as an int, so you get this:
cout << "Current balance is now: " << (m_bao.getBalance() + 10);
You probably meant to do this:
cout << "Current balance is now: " << m_bao.getBalance() << '\n';
Remember that in C++, + almost always means "add these two numbers".