In my program I am trying to call the void function from Main but I can't figure out the correct way.
Main is at the very bottom and void GetTicketType(char &Choice) is the function I need to call to cout the ticket type.
//---------------------------------------------------------------------------
// Purpose: This program simulates a ticket office for sporting events
// Author: TBA
// Date: TBA
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
using namespace std;
const char CASH = 'C';
const char CREDIT = 'D';
const char NOSEBLEED = 'N';
const char BOX_SEAT = 'B';
const char FIFTY_YARD_LINE = 'F';
const char STUDENT_SECTION = 'S';
const float NOSEBLEED_PRICE = 43.42;
const float BOX_SEAT_PRICE = 353.85;
const float FIFTY_YARD_LINE_PRICE = 94.05;
const float STUDENT_SECTION_PRICE = 19.99;
//---------------------------------------------------------------
// Function: ConfirmChoice
// Purpose: Confirms the users ticket purchase before processing payment
// Parameters: TicketType - The type of ticket selected
// Returns: true if the user confirms the selection, false otherwise
//--------------------------------------------------------------
bool ConfirmChoice(const char TicketType)
{
char Choice;
bool Confirmed;
// Print out their selection
cout << "\nYou have chosen to purchase ";
cout << fixed << setprecision(2);
switch (TicketType)
{
case NOSEBLEED:
cout << "Nosebleed ticket(s) at a price of $";
cout << NOSEBLEED_PRICE << ".\n";
break;
case BOX_SEAT:
cout << "Box Seat ticket(s) at a price of $";
cout << BOX_SEAT_PRICE << ".\n";
break;
case FIFTY_YARD_LINE:
cout << "Ticket(s) on the 50 yard line at a price of $";
cout << FIFTY_YARD_LINE_PRICE << ".\n";
break;
case STUDENT_SECTION:
cout << "Ticket(s) in the Student Section at a price of $";
cout << STUDENT_SECTION_PRICE << ".\n";
break;
}
// Confirm the selection
cout << "Do you wish to confirm your purchase? Enter Y or N: ";
cin >> Choice;
Choice = toupper(Choice);
while (Choice != 'Y' && Choice != 'N')
{
cout << "Invalid selection. Please enter either Y or N: ";
cin >> Choice;
Choice = toupper(Choice);
}
Confirmed = (Choice == 'Y');
// Check confirmation
if (Confirmed)
cout << "You have confirmed your choice.\n" << endl;
else
cout << "You not confirmed your choice.\n" << endl;
return (Confirmed);
}
//-------------------------------------------
// Function: CalculateChange
// Purpose: To output the change due
// Parameters: ChangeDue - The amount of change needed
// Returns: Nothing
//-------------------------------------------
void CalculateChange(const float ChangeDue)
{
int Change = 0;
int Dollars = 0;
int Quarters = 0;
int Dimes = 0;
int Nickels = 0;
int Pennies = 0;
// Compute change
Change = ChangeDue * 100;
Dollars = Change / 100;
Change = Change % 100;
Quarters = Change / 25;
Change = Change % 25;
Dimes = Change / 10;
Change = Change % 10;
Nickels = Change / 5;
Pennies = Change % 5;
// Print out change
cout << "Your change is \n\t";
cout << Dollars << " Dollars\n\t";
cout << Quarters << " Quarters\n\t";
cout << Dimes << " Dimes\n\t";
cout << Nickels << " Nickels\n\t";
cout << Pennies << " Pennies\n";
}
//---------------------------------------------------------------------------
// Function: CalculateCost
// Purpose: Calculate the cost of the ticket purchase(s) (num_tickets * price_per_ticket)
// Parameters: PricePerTicket - Ticket price based on the type of ticket
// Returns: The cost of purchasing the chosen number of tickets
//---------------------------------------------------------------------------
float CalculateCost(const float PricePerTicket)
{
int TicketCount;
float Cost;
cout << "How many tickets would you like? Please enter a positive integer value: ";
cin >> TicketCount;
while (TicketCount < 0)
{
cout << "Invalid entry. Please re-enter: ";
cin >> TicketCount;
}
Cost = PricePerTicket * TicketCount;
cout << "Your bill is: $" << fixed << setprecision(2) << Cost << endl;
return Cost;
}
//---------------------------------------------------------------------------
// Function: GetPaymentType
// Purpose: Ask the user how they want to pay, cash or credit
// Parameters: None
// Returns: Value is CREDIT or CASH (global character constants)
//---------------------------------------------------------------------------
char GetPaymentType()
{
char Choice;
// Print the main menu describing the ticket payment types
cout << "+-------------------------------------------------------+\n";
cout << "+ Welcome to our Ticket Office +\n";
cout << "+-------------------------------------------------------+\n";
cout << endl << endl;
// Cash or credit card (in upper case)
cout << "How would you like to pay?\n";
cout << "Enter C for cash or D for credit card: ";
cin >> Choice;
Choice = toupper(Choice);
while (Choice != CASH && Choice != CREDIT)
{
cout << "Invalid choice. Please enter C for cash or D for credit card: ";
cin >> Choice;
Choice = toupper(Choice);
}
return Choice;
}
//---------------------------------------------------------------------------
// Function: GetTicketType
// Purpose: Get the customer's choice between 4 types of tickets
// Parameters: Choice - Set to the user's choice
// Returns: Nothing
//---------------------------------------------------------------------------
void GetTicketType(char &Choice)
{
// Ask the customer what type of ticket s/he prefers to buy
cout << "\nWhat type of ticket would you like?\n";
cout << "\t" << NOSEBLEED << " for Nosebleed Section, Price = $";
cout << NOSEBLEED_PRICE << endl;
cout << "\t" << BOX_SEAT << " for Box Seats, Price = $";
cout << BOX_SEAT_PRICE << endl;
cout << "\t" << FIFTY_YARD_LINE << " for Seats on the Fifty Yard Line, Price = $";
cout << FIFTY_YARD_LINE_PRICE << endl;
cout << "\t" << STUDENT_SECTION << " for Student Section, Price = $";
cout << STUDENT_SECTION_PRICE << endl;
// Get ticket choice (in upper case)
cout << "Enter choice: ";
cin >> Choice;
Choice = toupper(Choice);
while (Choice != NOSEBLEED && Choice != BOX_SEAT &&
Choice != FIFTY_YARD_LINE && Choice != STUDENT_SECTION)
{
cout << "Invalid choice. Please re-enter: ";
cin >> Choice;
Choice = toupper(Choice);
}
}
//---------------------------------------------------------------------------
// Function: PayWithCash
// Purpose: Handles payment by cash. Asks the user for the money until
// they enter enough, then updates the ChangeDue parameter
// Parameters: Cost - The amount due for the purchase
// ChangeDue - The amount of change due to customer
// Returns: Nothing
//---------------------------------------------------------------------------
void PayWithCash(const float Cost, float &ChangeDue)
{
float CashOffered;
// Pay in cash
cout << "Please enter enough cash. Your bill is $" << Cost << ": $ ";
cin >> CashOffered;
// Check sufficiency
while (CashOffered < Cost)
{
cout << "That is not enough to pay for your purchase!\n"
<< " Please enter at least $" << Cost << ": ";
cin >> CashOffered;
}
// Calculate change
ChangeDue = CashOffered - Cost;
}
//---------------------------------------------------------------------------
// Function: PayWithCredit
// Purpose: Handles payment by credit. Basically, just prints a statement
// telling them that their card will be charged.
// Parameters: const float Cost - the amount due for the purchase
// Returns: Nothing
//---------------------------------------------------------------------------
void PayWithCredit(const float Cost)
{
cout << "Your credit card will be billed for $" << Cost << ".\n";
}
//---------------------------------------------------------------------------
// Function: main
// Purpose: This is the main program that calls functions above.
// Parameters: None
// Returns: Nothing
//---------------------------------------------------------------------------
int main()
{
// Declarations
char TChoice ; // Ticket type: Nosebleed, box seats etc..
TChoice << GetTicketType( &TChoice);
char PChoice = GetPaymentType() ; // Payment choice: cash or credit card
bool Confirmed; // Did the user confirm the selection
float Cost; // The cost of the ticket puchased
float ChangeDue; // The amount of change owed (for cash purchases)
// Print your name and UAID
// Get the choice of payment type
// Get the choice of ticket type
GetTicketType(TChoice );
{
cout << "You have chosen the " << TChoice << "tickets. " <<".\n";
}
// Confirm the selection
// If they confirm the purchase
// Call functions to figure out the price of ticket purchase(s)
// Be sure to use the named constants
// Handle the payment
// Say goodbye
// Else
// Cancel the purchase
return 0;
}
Change
TChoice << GetTicketType( &TChoice);
To Simple
GetTicketType( &TChoice);
Since TChoice << GetTicketType( &TChoice); is doing bitwise left shift operation it will expect an integer type after <<.Your function is returning nothing(void) and thus causes an error.
It looks like you're getting an error on this line:
TChoice << GetTicketType( &TChoice);
You're calling GetTicketType and expecting to use the result. Is that really what you want to do, since it's a void function?
Related
I was tasked to create an ATM mock program and my problem is overwriting the money and PIN variables with the information that the user will enter.
Here it is:
#include <iostream>
using namespace std;
void Check(int money) { cout << "Your current balance is: " << money << endl; }
void Deposit(int money) {
int deposit;
cout << "Please enter the amount of cash you wish to deposit.\n";
cin >> deposit;
money += deposit;
cout << "Your new balance is: " << money << endl;
}
void Withdraw(int money) {
int withdraw;
cout << "Please enter the amount of cash you wish to withdraw.\n";
cin >> withdraw;
money -= withdraw;
cout << "Your new balance is: " << money << endl;
}
void Interest(int money) {
money += money * 0.05;
cout << "Your money with interest is: " << money << endl;
}
void Penalty(int money) {
if (money < 5000) {
money -= money * 0.02;
cout << "Your penalty is: " << money << endl;
} else
cout << "Your account will not incur a penalty because you are above the "
"minimum threshold.\n";
}
void ChangePIN(int PIN) {
int p;
cout << "Enter a new PIN: ";
cin >> p;
PIN = p;
cout << "Your new PIN is: " << PIN << endl;
}
int main() {
int money = 5000, PIN = 1234, EPIN;
cout << "Enter your PIN (Default PIN is 1234): \n";
cin >> EPIN;
if (EPIN == PIN) {
int choice;
cout << "Welcome!\n"
<< "1 - Check available balance \n"
<< "2 - Deposit cash \n"
<< "3 - Withdraw cash \n"
<< "4 - Compute for the interest of your account(5%)\n"
<< "5 - Compute for the penalty of having a balance below 5000 (2%) \n"
<< "6 - Change your PIN\n"
<< "7 - Exit\n"
<< "Your choice: ";
cin >> choice;
switch (choice) {
case 7: {
break;
}
{
case 1: {
Check(money);
break;
}
case 2: {
Deposit(money);
break;
}
case 3: {
Withdraw(money);
break;
}
case 4: {
Interest(money);
break;
}
case 5: {
Penalty(money);
break;
}
case 6: {
ChangePIN(PIN);
break;
}
}
}
return 0;
}
}
As you can see I'm pretty much a beginner at this. My problem is the money and PIN have the default values of 5000 and 1234 respectively. Now, I need to make the user be able to change these values but once I use return main() they get assigned the same starting values again, What would be the best workaround for this? I thought of using some sort of accumulator for this but I'd like some advice first.
You can simply do this by using a while loop.
Run an infinite while loop and break it whenever you want to exit from the program.
Here is the code:
#include <iostream>
using namespace std;
void Check(int money) { cout << "Your current balance is: " << money << endl; }
void Deposit(int money) {
int deposit;
cout << "Please enter the amount of cash you wish to deposit.\n";
cin >> deposit;
money += deposit;
cout << "Your new balance is: " << money << endl;
}
void Withdraw(int money) {
int withdraw;
cout << "Please enter the amount of cash you wish to withdraw.\n";
cin >> withdraw;
money -= withdraw;
cout << "Your new balance is: " << money << endl;
}
void Interest(int money) {
money += money * 0.05;
cout << "Your money with interest is: " << money << endl;
}
void Penalty(int money) {
if (money < 5000) {
money -= money * 0.02;
cout << "Your penalty is: " << money << endl;
} else
cout << "Your account will not incur a penalty because you are above the "
"minimum threshold.\n";
}
int ChangePIN(int PIN) {
int p;
cout << "Enter a new PIN: ";
cin >> p;
cout << "Your new PIN is: " << PIN << endl;
return p;
}
int main() {
int money = 5000, PIN = 1234;
while(1){ // run an infinite loop
int EPIN;
cout << "Enter your PIN (Default PIN is 1234): \n";
cin >> EPIN;
if (EPIN == PIN) {
int choice;
cout << "Welcome!\n"
<< "1 - Check available balance \n"
<< "2 - Deposit cash \n"
<< "3 - Withdraw cash \n"
<< "4 - Compute for the interest of your account(5%)\n"
<< "5 - Compute for the penalty of having a balance below 5000 (2%) \n"
<< "6 - Change your PIN\n"
<< "7 - Exit\n"
<< "Your choice: ";
cin >> choice;
switch (choice) {
case 7: {
return 0; // breaking condition
}
{
case 1: {
Check(money);
break;
}
case 2: {
Deposit(money);
break;
}
case 3: {
Withdraw(money);
break;
}
case 4: {
Interest(money);
break;
}
case 5: {
Penalty(money);
break;
}
case 6: {
PIN = ChangePIN(PIN);
break;
}
}
}
}
}
return 0;
}
Does this answer your question?
In the output, I keep getting -"dollars" and -"cents" instead of positives as shown in the picture.
I have used a class named savings account to set initial balance, deposit and withdraw. And I am asked to use 1 object that prompts the user for input and another that uses overload constructor to initialize dollar and cents.
// Include Section
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class SavingsAccount
{
public:
SavingsAccount();
SavingsAccount(int, int);
void setInitial(int, int);
void setDeposit(int, int);
void setWithdraw(int, int);
void output();
private:
int dollars;
int cents;
};
// Main Function
int main()
{
// object declaration
// Bank 1
SavingsAccount bank1; //has its values set during definition by the user
//Bank 2
SavingsAccount bank2(200, 50); //uses the constructor to store values into member variables
bank2.setDeposit(40, 50);
bank2.setWithdraw(100, 98);
bank2.output();
cout << "\n\n";
// Variable declaration
string repeat;
int d, c;
int choice;
// Prompt for initial balance
cout << "welcome to your savings account! Please fill in the appropriate information.\n\n";
cout << "Initial balance (dollars): ";
cin >> d;
cout << "Initial balance (cents): ";
cin >> c;
bank1.setInitial(d, c);
do
{
cout << "Pick an option: " << endl
<< "1. Deposit money" << endl
<< "2. Withdraw money" << endl;
cin >> choice;
switch (choice)
{
case 1:
cout << "Deposit amount (dollars): ";
cin >> d;
cout << "Deposit amount (cents): ";
cin >> c;
bank1.setDeposit(d, c);
break;
case 2:
cout << "Withdraw amount (dollars): ";
cin >> d;
cout << "Withdraw amount (cents): ";
cin >> c;
bank1.setWithdraw(d, c);
break;
case 3:
break;
default:
while (choice != 1 && choice != 2)
{
cout << "Invalid choice, enter 1 or 2: \n";
cin >> choice;
}
}
// Display output
bank1.output();
// Prompt for continuing
cout << "\nWould you like to keep going? (y or Y for yes)";
cin >> repeat;
}while (repeat == "y" || repeat == "Y");
cout << "End Program.\n\n";
return 0;
}
SavingsAccount::SavingsAccount()
{
dollars = 0;
cents = 0;
}
SavingsAccount::SavingsAccount(int newD, int newC)
{
dollars = newD;
cents = newC;
cout << "Your initial balance is $" << dollars << "." << cents << endl;
}
void SavingsAccount::setInitial(int initialD, int initialC)
{
while (initialC >= 100)
{
initialC = initialC - 100;
initialD++;
}
dollars = initialD;
cents = initialC;
cout << "Your initial balance is $" << dollars << "." << cents << endl;
}
void SavingsAccount::setDeposit(int depD, int depC)
{
while (depC >= 100)
{
depC = depC - 100;
depD++;
}
dollars = depD + dollars;
cents = depC + cents;
cout << "Depositing $" << depD << "." << depC << " to your account...\n";
}
void SavingsAccount::setWithdraw(int withD, int withC)
{
while (withC >= 100)
{
withC = withC - 100;
withD++;
}
if (withD > dollars)
{
cout << "Not enough money to be withdrawn.\n";
}
else
{
dollars = withD - dollars;
cents = withC - cents;
cout << "Withdrawing $" << withD << "." << withC << " from your account...\n";
}
}
void SavingsAccount::output()
{
cout << "dollars = " << dollars << " cents = " << cents << endl;
}
You ask How can I find the mistake I am making in my C++ code? (and not What is the mistake I am making in my C++ code?)
Part of the answer to your question is, and this is especially applicable to small programs when you first start learning to program, to trace the execution of your program with pencil and paper. Then, as your programs become longer and more complicated, start watching their execution with a debugger.
I am writing a program that simulates an ATM. So it tracks account balances, withdrawals and deposits in a very basic matter.
Everything works well during the first iteration, but if I go to make two or more deposits or withdrawals, the account balances default back to the original amount.
Here is an example of what is currently happening: I have $1,000 in my account initially. I make a deposit of $50. It prints out that I now have $1,050 in my account and asks if I would like to perform any other actions. (This is all good). If I select that I want to make another deposit of $100, it says my new account balance is $1,100 instead of $1,150. It does not store my latest account balance when I perform new withdrawals or deposits.
The second (less important) issue is that each time a withdrawal is made, there is a $2.50 fee for each withdrawal that also gets subtracted from my account balance.
I have not learned loops yet, only Cases, If statements and If Else Statements.
Is it possible to do what I want to do? Below is my code. Thank you in advance! This is my first time posting, so if I have pasted my code wrong, I apologize.
#include <iostream>
#include <string>
using namespace std; // opens library for "cout"
int main()
{
float test;
int logout;
string name;
float balance;
float fee;
int choice;
float withdraw;
float deposit;
float bonus;
bonus = 2.50;
balance = 1572.36;
fee = 12.50;
char answer;
cout << "Hello, thank you for banking with Pallet Town Bank.\n";
cout << "Please enter your name. ";
cin >> name;
cout << "Hello " << name << ". Your current balance is $" << balance << ".\n";
cout << "There will be a a service fee of $12.50 subtracted from your "
"account.\n";
cout << "Your updated balance will be $" << balance - fee << " \n";
cout << "What would you like to do today?\n";
do
{
cout << "\n1 - Current Balance\n2 - Withdraw\n3 - deposit\n4 - Log "
"Out\nOption: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "\nCurrent Balance is " << balance - fee - withdraw + deposit
<< " \n";
cout << "Would you like to take any other actions today?\n";
break;
case 2:
cout << "\nWithdraw - How much would you like to withdraw? $";
cin >> withdraw;
cout << "Your new balance after withdrawing $" << withdraw << " will be $"
<< balance - fee - withdraw + deposit << "\n";
cout << "Would you like to take any other actions today?\n";
break;
case 3:
cout << "\nDeposit - How much would you like to deposit? $";
cin >> deposit;
test = balance - fee - withdraw + deposit;
cout << "Your new balance after depositing $" << deposit << " will be $"
<< test << endl; //<<balance - fee - withdraw + deposit<<"\n";
cout << "Would you like to take any other actions today? Y or N \n";
cin >> answer;
cout << answer;
if (answer == 'y' || 'Y')
{
test = balance - fee - withdraw + deposit + deposit;
cout << "Your new balance after depositing $" << deposit << " will be $"
<< test << endl;
}
// cout <<"Your new balance after depositing $"<<deposit<<" will be $"
// <<test<< endl; //<<balance - fee - withdraw + deposit<<"\n";
// cout <<"Would you like to take any other actions today?\n";
break;
case 4:
cout << "\nLog Out - Thank you for banking with Pallet Town Bank. Have "
"a great day!";
}
} while (choice != 4);
}
The main issue, as Alan Birtles points out, is that you never update the balance value; you just store the temporary calculations in the test variable.
Here's how you could change your code. I tried interpreting the expected behaviour of the program as best I could from the text:
#include <iostream>
#include <string>
using namespace std;
int main()
{
const double fee = 12.50;
double balance = 1572.36;
cout << "Hello, thank you for banking with Pallet Town Bank.\n";
cout << "Please enter your name. ";
string name;
cin >> name;
cout << "Hello " << name << ". Your current balance is $" << balance << ".\n";
cout << "There will be a a service fee of $12.50 subtracted from your "
"account.\n";
cout << "Your updated balance will be $" << (balance -= fee) << " \n";
cout << "What would you like to do today?\n\n";
while (true)
{
cout << "1 - Current Balance" << '\n'
<< "2 - Withdraw" << '\n'
<< "3 - deposit" << '\n'
<< "4 - Log Out" << '\n'
<< "Option: ";
int choice;
cin >> choice;
cout << endl;
if (choice == 4) break;
switch (choice)
{
case 1:
cout << "Current Balance is " << balance << '\n';
break;
case 2:
cout << "Withdraw - How much would you like to withdraw? $";
double withdraw;
cin >> withdraw;
cout << "Your new balance after withdrawing $" << withdraw << " will be $"
<< (balance -= withdraw) << '\n';
break;
case 3:
cout << "Deposit - How much would you like to deposit? $";
double deposit;
cin >> deposit;
cout << "Your new balance after depositing $" << deposit << " will be $"
<< (balance += deposit) << '\n';
break;
}
cout << "Would you like to take any other actions today? ";
char answer;
cin >> answer;
cout << endl;
if (toupper(answer) == 'N') break;
}
cout << "Log Out - Thank you for banking with Pallet Town Bank. Have a great day!" << endl;
}
Live demo
Changes
First of all, every time a modification is made (withdrawal/deposit), we need to actually update the balance. We can do so by using the += or -= operators (called "compound assignment" operators): when writing balance += x, we're adding x to balance, and when writing balance -= x we're subtracting. These expressions are equivalent to balance = balance + x and balance = balance - x, respectively.
I moved the "Would you like to [...]" part outside the switch statement, to avoid repeating it in each case.
As pointed out in the comments, answer == 'Y' || 'y' isn't the same as answer == 'Y' || answer == 'y'. I changed that to toupper(answer) == 'Y'.
I moved the logout handling outside the while loop, so that whenever the loop terminates, the logout message is always shown. That allows us to remove case 4 from the switch statement, by checking at the beginning if choice == 4 and then breaking out of the loop accordingly. This also implies the loop becomes a while (true) loop. Probably there is a more elegant way.
Even better
If you're confortable with functions, I would suggest refactoring the code, isolating each operation individually:
#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
using namespace std;
const int FEE = 1250; // fee in cents
//---- Utilities ----//
string moneyString(int cents) {
ostringstream oss;
oss << cents/100 << '.' << cents % 100;
return oss.str();
}
int toCents(double money) {
return int(round(money*100));
}
int getMoney() {
double money;
cin >> money;
return toCents(money);
}
//---- User input ----//
// Available choices
enum Choices {
BALANCE = 1,
WITHDRAW = 2,
DEPOSIT = 3,
LOGOUT = 4
};
short int getChoice() {
short int choice = 0;
while (choice < 1 or choice > 4) {
cout << "1 - Current Balance" << '\n'
<< "2 - Withdraw" << '\n'
<< "3 - deposit" << '\n'
<< "4 - Log Out" << '\n'
<< "Option: ";
string input;
cin >> input;
choice = atoi(input.c_str());
cout << endl;
}
return choice;
}
bool userWantsMoreActions() {
cout << "Would you like to take any other actions today? ";
char answer;
cin >> answer;
cout << endl;
return toupper(answer) == 'Y';
}
//---- Actions ----//
void greeting(double &balance) {
cout << "Hello, thank you for banking with Pallet Town Bank.\n";
cout << "Please enter your name. ";
string name;
cin >> name;
cout << "Hello " << name << ". Your current balance is $" << moneyString(balance) << ".\n";
cout << "There will be a a service fee of $12.50 subtracted from your account.\n";
cout << "Your updated balance will be $" << moneyString(balance -= FEE) << " \n";
cout << "What would you like to do today?\n\n";
}
void printBalance(const double &balance) {
cout << "Current Balance is " << balance << '\n';
}
void withdraw(double &balance) {
cout << "Withdraw - How much would you like to withdraw? $";
int withdraw = getMoney();
cout << "Your new balance after withdrawing $" << withdraw << " will be $"
<< (balance -= withdraw -= FEE) << '\n';
}
void deposit(double &balance) {
cout << "Deposit - How much would you like to deposit? $";
int deposit = getMoney();
cout << "Your new balance after depositing $" << moneyString(deposit)
<< " will be $" << moneyString(balance += deposit -= FEE) << '\n';
}
int main()
{
// Initialize a sample session:
double balance = 157236;
greeting(balance);
while (true)
{
short int choice = getChoice();
if (choice == Choices::BALANCE) printBalance(balance);
else if (choice == Choices::WITHDRAW) withdraw(balance);
else if (choice == Choices::DEPOSIT) deposit(balance);
else if (choice == Choices::LOGOUT) break;
if (not userWantsMoreActions()) break;
}
cout << "Log Out - Thank you for banking with Pallet Town Bank. Have a great day!" << endl;
}
Live demo
I am working on a project for class and I have pretty much completed all my code I just have one issue (THE CODE IS IN C++). I'm not too great at using boolean functions especially in the case for this program. If you guys could help me write or push me in the right direction for this code I'd appreciate it. This program is supposed to be a Soda Machine program made of structs. My question is how do I pass the array to the boolean function in order to check if there are any drinks left for the one that the customer wants to purchase. If there are no drinks left, the program will print out "Sorry we are sold out. Please make another selection." If there are still drinks available then just do nothing and continue with the program. It will pretty much validate the amount of drinks left. I attempted to write the function but I'm not sure if it is correct, I will post it for you guys to take a look at it. If you guys need any other info please let me know. Thanks for the help before guys.
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
struct Machine
{
string name;
double cost;
int drinks;
};
int displayMenu(int choice);
double inputValidation(double);
bool drinksRemaining(); // this is the function that will check if there are any drinks of the choice left
int displayMenu(int choice)
{
cout << "SOFT DRINK MACHINE\n";
cout << "------------------\n";
cout << "1) Cola ($0.65)\n";
cout << "2) Root Beer ($0.70)\n";
cout << "3) Lemon-Lime ($0.75)\n";
cout << "4) Grape Soda ($0.85)\n";
cout << "5) Water ($0.90)\n";
cout << "6) Quit Program\n";
cout << endl;
cout << "Please make a selection: ";
cin >> choice;
return choice;
}
double inputValidation(double amount)
{
while (amount < 0.00 || amount > 1.00)
{
cout << "Please enter an amount between $0.00 and $1.00.\n";
cout << "It should also be equal to or greater than the drink price : \n";
cin >> amount;
}
return amount;
}
bool drinksRemaining() // this is the function that I am having trouble with
{
if (drinks <= 0)
{
cout << "Sorry we are out of this drink. Please choose another one.";
cin >> drinkChoice;
return true;
}
else
{
return false;
}
}
int main()
{
const int DRINK_NUMS = 5;
int selection = 0;
double amountInserted = 0.00;
double changeReturned = 0.00;
double profit = 0.00;
Machine drink[DRINK_NUMS] = { { "Cola", .65, 20 }, { "Root Beer", .70, 20 }, { "Lemon-Lime", .75, 20 }, { "Grape Soda", .85, 20 }, { "Water", .90, 20 } };
do
{
profit += amountInserted - changeReturned;
selection = displayMenu(selection);
if (selection == 1)
{
cout << "Please enter the amount you want to insert:\n";
cin >> amountInserted;
inputValidation(amountInserted);
changeReturned = amountInserted - drink[0].cost;
cout << setprecision(2) << fixed << "CHANGE : $" << changeReturned << endl;
drink[0].drinks--;
}
else if (selection == 2)
{
cout << "Please enter the amount you want to insert:\n";
cin >> amountInserted;
inputValidation(amountInserted);
changeReturned = amountInserted - drink[1].cost;
cout << setprecision(2) << fixed << "CHANGE : $" << changeReturned << endl;
drink[1].drinks--;
}
else if (selection == 3)
{
cout << "Please enter the amount you want to insert.\n";
cin >> amountInserted;
changeReturned = amountInserted - drink[2].cost;
cout << setprecision(2) << fixed << "CHANGE : $" << changeReturned << endl;
drink[2].drinks--;
}
else if (selection == 4)
{
cout << "Please enter the amount you want to insert.\n";
cin >> amountInserted;
changeReturned = amountInserted - drink[3].cost;
cout << setprecision(2) << fixed << "CHANGE : $" << changeReturned << endl;
drink[3].drinks--;
}
else if (selection == 5)
{
cout << "Please enter the amount you want to insert.\n";
cin >> amountInserted;
changeReturned = amountInserted - drink[4].cost;
cout << setprecision(2) << fixed << "CHANGE : $" << changeReturned << endl;
drink[4].drinks--;
}
else if (selection == 6)
{
cout << endl;
cout << "SOFT DRINK MACHINE REPORT\n";
cout << "--------------------------\n";
cout << "Total amount earned: $" << profit << endl;
cout << endl;
}
else
{
cout << "Invalid selection. Please try again.";
displayMenu(selection);
}
}while (selection != 6);
system("PAUSE");
return 0;
}
The function needs an object or a reference to an object of type Machine.
bool drinksRemaining(Machine const& m);
and can be implemented very simply:
bool drinksRemaining(Machine const& m)
{
return (m.drinks > 0);
}
You can use it as:
if (selection == 1)
{
if ( drinksRemaining(drink[0]) )
{
cout << "Please enter the amount you want to insert:\n";
cin >> amountInserted;
inputValidation(amountInserted);
changeReturned = amountInserted - drink[0].cost;
cout << setprecision(2) << fixed << "CHANGE : $" << changeReturned << endl;
drink[0].drinks--;
}
else
{
cout << "Sorry we are out of this drink. Please choose another one.";
}
}
I have been working on this project that simulates a bank account. The user can deposit, withdraw, and have all the withdraws and deposits displayed on the screen. At the top of the selection menu needs to be the current balance. Like so, SAVINGS : 100. And whenever I deposit money or withdraw money I need that balance to change to the correct amount. The amount starts at $100. If I deposit or withdraw money it will work perfectly the first time, but on the second time it gets reset back to $100 and then the transaction is done. How can I make the balance stay the correct amount without it resetting? This is a school project and I am not looking for someone to provide me the code. I am just seeking some tips or guidance in the right direction. Here is the code for my int main() :
int main ()
{
saving sa;
creditCard cca;
checking ca;
string n;
int option;
int exit = 1;
int x = 1;
do{
cout << endl;
cout << "Checking Balance:" << ca.getBalance() << " " << "Savings balance:" << sa.getBalance() << " " << "Credit Card balance:" << cca.getBalance() << endl;
cout << endl;
cout << " (1) Savings Deposit " << endl;
cout << " (2) Savings withdrawel " << endl;
cout << " (3) Checking Deposit " << endl;
cout << " (4) Write A Check " << endl;
cout << " (5) Credit Card Payment " << endl;
cout << " (6) Make A Charge " << endl;
cout << " (7) Display Savings " << endl;
cout << " (8) Display Checkings " << endl;
cout << " (9) Display Credit Card " << endl;
cout << " (0) Exit " << endl;
cin >> option;
switch ( option )
{
case 1 : {
double SamtD;
cout << " Please enter how much you would like to deposit into savings " << endl;
cin >> SamtD;
sa.makeDeposit(SamtD);
break;
};
case 2 : {
int SamtW;
cout << " Please enter how much you would like to withdraw "<< endl;
cin >> SamtW;
sa.doWithdraw(SamtW);
break;
}
case 3 : {
double CamtD;
cout << " Please enter how much you would like to deposit into checkings " << endl;
cin >> CamtD;
ca.makeDeposit(CamtD);
break;
}
case 4 : {
double CamtW;
int chkNum;
cout << " Please enter how much you wrote on the check " << endl;
cin >> CamtW;
cout << " Please enter the check number " << endl;
cin >> chkNum;
ca.writeCheck(chkNum, CamtW);
break;
}
case 5 : {
double CCmkP;
cout << " Please enter the amount you would like to deposit " << endl;
cin >> CCmkP;
cca.makePayment(CCmkP);
break;
}
case 6 : {
double DoC;
string Nm;
cout << " Please enter the amount charged to your credit card " << endl;
cin >> DoC;
cout << " Please enter where the charge was made " << endl;
cin >> Nm;
getline(cin, Nm);
cca.doCharge(Nm,DoC);
break;
}
case 7 : {
sa.display();
break;
}
case 8 : {
ca.display();
break;
}
case 9 : {
cca.display();
break;
}
case 0 : exit = 0;
break;
default : exit = 0;
cout << " ERROR ";
}
}
while(exit==1);
return 0;
}
and here is were the balance is being set :
double curbalance = 100;
void account::setBalanceD(double balance) // This is for deposit
{
itsBalance = balance;
}
void account::setBalanceW(double balance) // This is for withdraw
{
double newBalance = curBalance - balance;
itsBalance = newBalance;
}
double account::getBalance()
{
return itsBalance;
}
and here is the code that option 2 in my menu would be calling :
int saving:: doWithdraw(int amount)
{
if (amount > 0)
{
for (int i = 9; i != 0; i--)
{
last10withdraws[i] = last10withdraws[i-1];
}
last10withdraws[0] = amount;
setBalanceW(amount);
}
else
{
cout << " ERROR. Number must be greater then zero. " << endl;
}
return 0;
}
Any ideas? I just cannot get the balance to remain accurate.
The problem is that your setBalanceW() function never deducts from curBalance, so it stays at 100.
void account::setBalanceW(double balance) // This is for withdraw
{
curBalance -= balance;
}
Your other references should be to curBalance as well, as there should only be one current balance.
void account::setBalanceD(double balance) // This is for deposit
{
curBalance += balance;
}
double account::getBalance()
{
return curBalance;
}
The best solution, though (presuming that itsBalance is a member of the account class, would be to eliminate curBalance altogether, and just open your main() with an initial deposit:
int main ()
{
saving sa;
creditCard cca;
checking ca;
sa.makeDeposit(100.0);
/* other code */
}
/* Note no curBalance variable? */
void account::setBalanceW(double balance) // This is for withdraw
{
itsBalance -= balance;
}
void account::setBalanceD(double balance) // This is for deposit
{
itsBalance += balance;
}
double account::getBalance()
{
return itsBalance;
}
Your implementation for performing a deposit appears to be incorrect. It should be:
void account::setBalanceD(double balance) // This is for deposit
{
itsBalance += balance;
}
Notice that we are now adding the amount being deposited to the current balance, instead of explicitly setting it's value. Similarly as Ken pointed out the same applies to performing a withdraw.
void account::setBalanceW(double balance) // This is for withdraw
{
itsBalance -= balance;
}