I'm making a simple c++ atm program, but I'm having trouble with getting the balance to change after I make a deposit or withdraw.
// C++ ATM
#include "std_lib_facilities.h"
int main()
{
bool card_is_inserted = false;
double balance = 0.0;
//double new_balance = balance;
// HOME
//Starts over if variable is false
while (card_is_inserted == false)
{
cout << "Wellcome to Well's Fargo ATM " << '\n'
<< "Insert card Yes or No"<< endl;
string request;
getline(cin,request);
// Function is needed for aceppting different no's and yes's
//-=-=-=--=-==--=-=-==-==-=--==--=-=-
// loads atm
if (request == "yes")
{
cout << "Alright, Your current balance is:" << endl
<< balance << endl;
card_is_inserted = true;
}
// home
string option = "cancel";
while (card_is_inserted == true)
{
cout << "Would you like to withdraw or deposit? (Cancel)"<< endl;
getline(cin,option);
double cash_ = 0;
if (option == "deposit")
{
cout << "How much money would you like to deposit?" << endl;
cin >> cash_;
double new_deposit_balance = balance + cash_;
cout << "You placed: $" << cash_ << endl
<< "Your New Balance is: $" << new_deposit_balance << endl;
}
if (option == "withdraw")
{
cout << "How much money would you like to withdraw?" << endl;
cin >> cash_;
double new_witdraw_balance = balance - cash_;
if(balance <= 0)
{
cout << "You don't have: $" << cash_ << endl;
}
else
{
cout << "You toke: $" << cash_ << endl
<< "Your New Balance is: $"<< new_witdraw_balance << endl;
}
}
if (option == "cancel")
{
cout << "Ok, bye" << endl;
card_is_inserted = false;
}
}
}
}
example: I type yes to make a deposit(or withdraw) and then place a simple double like 12.50 then it shows me my current balance which will be 12.50; afterward I want to make a withdraw of 12.00 with .50 left. But I cant because the balance variable didn't store my previous value which was 12.50. I tried making "double new_balance = balance" but doesn't work like in swift.
You are not setting balance to new_witdraw_balance or new_deposit_balance.
double new_deposit_balance = balance + cash_; doesn't set the balance value because you are bring in the value of balance, but you are not assigning the outcome of balance + cash_ to balance.
You need to put something like balance = new_witdraw_balance; and balance = new_deposit_balance; at the end of each if after cout statement.
if(option == "deposit")
{
cout << "How much money would you like to deposit?" << endl;
cin >> cash_;
double new_deposit_balance = balance + cash_;
cout << "You placed: $" << cash_ << endl << "Your New Balance is: $" << new_deposit_balance << endl;
balance = new_deposit_balance; // this
}
if(option == "withdraw")
{
cout << "How much money would you like to withdraw?" << endl;
cin >> cash_;
double new_witdraw_balance = balance - cash_;
if(balance <= 0)
{
cout << "You don't have: $" << cash_ << endl;
}
else
{
cout << "You toke: $" << cash_ << endl << "Your New Balance is: $"<< new_witdraw_balance << endl;
balance = new_witdraw_balance; // and this
}
}
The line double new_deposit_balance = balance + cash_; only assigns the new balance to new_deposit_balance, but then you don't do anything with that variable (except print the value). If you want the new balance to persist, you actually need to modify balance, not new_deposit_balance, so something like balance = balance + cash_; or balance += cash_;.
The variable double new_deposit_balance only exists in the if-block it's defined in, so once you leave the if-block, you lose the information in new_deposit_balance. On the other hand, since balance is defined outside your if-blocks and while-loops, its value will persist throughout your ATM operations.
Of course, you'd also need to apply the same fix to new_witdraw_balance.
Related
I am writing a "vending machine" program and I need to have 5 items where 3 items cost an integer amount and the other 2 cost a decimal amount.
I am only using if statements in this code, but there is an error with my cost variable.
What did I do wrong?
Code below:
#include <iostream>
using namespace std;
int main() {
cout << "Vending Machine" << endl;
cout << "----Items------" << endl;
cout << "1. Popcorn: $2" << endl;
cout << "2. Coconut Clusters: $3" << endl;
cout << "3. Granola Bar: $2.50" << endl;
cout << "4. Trail Mix: $1.50" << endl;
cout << "5. Chocolate: $1" << endl;
cout << "Enter you selection: " << flush;
int input;
cin >> input;
if (input == 1) {
cout << "You added Popcorn to your cart." << endl;
float cost = 2;
cout << "Your total is $" << cost << endl;
}
if (input == 2) {
cout << "You added Coconut Clusters to your cart." << endl;
float cost = 3;
cout << "Your total is $" << cost << endl;
}
if (input == 3) {
cout << "You added Granola Bar to your cart." << endl;
float cost = 2.50;
cout << "Your total is $" << cost << endl;
}
if (input == 4) {
cout << "You added Trail Mix to your cart." << endl;
float cost = 1.50;
cout << "Your total is $" << cost << endl;
}
if (input == 5) {
cout << "You added Chocolate to your cart." << endl;
float cost = 1;
cout << "Your total is $" << cost << endl;
}
cout << "Pay amount: " << flush;
float money;
cin >> money;
if (money > cost) {
float change = money-cost;
cout << "Thank you! You have $" << change << " change." << endl;
}
if (money == cost) {
cout << "Thank you! Have a nice day!." << endl;
}
if (money < cost) {
float amountOwed = cost-money;
cout << "Please insert another $" << amountOwed << endl;
cout << "Enter amount: " << flush;
float payment;
cin >> payment;
if (payment > amountOwed) {
float change2 = payment-cost;
cout << "Thank you! You have $" << change2 << " change." << endl;
}
if (payment == amountOwed) {
cout << "Thank you! Have a nice day!." << endl;
}
if (payment < amountOwed) {
cout << "Sorry, you did not enter enough money. Your cart has emptied." << endl;
}
}
return 0;
}
The problem is that you are doing the following:
int main()
{
[...]
if (input == 1) {
cout << "You added Popcorn to your cart." << endl;
float cost = 2;
cout << "Your total is $" << cost << endl;
}
[...]
if (money > cost) {
[...]
}
[...]
}
The scope of the variable cost is limited to the if block, because that is where you declare it. Therefore, the variable does not exist anymore when you evaluate the expression money > cost.
To fix this, you should instead declare the variable cost in the main block scope of the function, like this:
int main()
{
float cost;
[...]
if (input == 1) {
cout << "You added Popcorn to your cart." << endl;
cost = 2;
cout << "Your total is $" << cost << endl;
}
[...]
if (money > cost) {
[...]
}
[...]
}
Update: you've just changed your question to add float cost = 0; in a suitable place. Now you need to remove the float keyword from the attempted assignments inside each if (input == block: e.g. change float cost = 2.50; to cost = 2.50; so it changes the function-scope cost variable, instead of creating an extra if-scope variable.
Addressing your original problem...
Your if blocks...
if (input == 3) {
cout << "You added Granola Bar to your cart." << endl;
float cost = 2.50;
cout << "Your total is $" << cost << endl;
}
...each create a float cost variable local to the scope of that if, so after the } the value of cost that you set is gone. Instead, you need to have:
float cost;
Before your first if (input == ... statement, so its lifetime extends to the end of the enclosing function scope (i.e. until main() returns).
"Can I declare a variable in an “if statement”?"
Yes. For example:
if (auto foo = bar())
The variable foo will be valid inside the body of the if statement and will be initialized to whatever bar() returns and the body of the if will be entered if foo converts to a bool value of true.
Since C++17 you can also do:
if (auto foo = bar(); foo == 42)
Again, the variable foo will be declared and valid inside the if and initialized by bar(), but you now have more control over when to enter the if body.
When I try to compile your code, I get the following error message:
Error: ‘cost’ was not declared in this scope
In order to fix this error, you just need to declare cost variable in the function's main block scope, for example like this:
int main()
{
float cost;
[...]
}
I'm to write a function to withdraw money from array containing initial balance.
If the balance is insufficient, then a warning message along with user's balance is displayed.
The user is prompted to enter the new amount for a second time, if the amount is OK withdraw operation is completed and balance is updated and menu is displayed.
If balance is still insufficient, withdraw operation is terminated and menu is displayed.
Below is the code which works if I try to enter amount which is lower than the balance for the first time. But does not update the balance well if I enter the valid amount on the second try.
double withdrawAmount(int pin, double balance[]){
double amount;
double newBalance = balance[pin];
int withdrawTrial = 0;
do{
system("cls");
cout << "-----------------------------------------" << endl;
cout << "\tWELCOME TO EDON ATM" << endl;
cout << "-----------------------------------------" << endl;
cout << endl;
cout << "Please enter amount to be withdrawn: $";
cin >> amount;
if (balance[pin] < amount){
cout << endl;
cout << "Insufficient Balance!" << endl;
cout << "Your balance is: $" << balance[pin] << endl;
cout << endl;
while (withdrawTrial < 1){
withdrawTrial++;
cout << "Please enter amount to be withdrawn: $";
cin >> amount;
}
if (withdrawTrial == 1){
menuBoard();
return newBalance;
}
}
balance[pin] -= amount;
newBalance = balance[pin];
} while (amount < 0);
return newBalance;
}
You are not following the instructions correctly. You are not validating the user's input on the second prompt. Get rid of the while (withdrawTrial < 1) loop completely. Prompt once and validate. If the amount is greater than the available balance then prompt again and re-validate. If the amount is still greater than the available balance then exit. No loops are needed (unless you want to validate the user is actually entering a floating-point number and nothing else).
Also, you should not be calling menuBoard() inside of withdrawAmount() itself, you should be calling it after withdrawAmount() exits.
double inputDollars(const char *prompt){
double value;
do {
cout << prompt << ": $";
if (cin >> value)
break;
cout << endl;
cout << "Invalid Input!" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
while (true);
return value;
}
double withdrawAmount(int pin, double balance[]){
double amount;
system("cls");
cout << "-----------------------------------------" << endl;
cout << "\tWELCOME TO EDON ATM" << endl;
cout << "-----------------------------------------" << endl;
cout << endl;
amount = inputDollars("Please enter amount to be withdrawn");
if (balance[pin] < amount){
cout << endl;
cout << "Insufficient Balance!" << endl;
cout << "Your balance is: $" << balance[pin] << endl;
cout << endl;
amount = inputDollars("Please enter amount to be withdrawn");
if (balance[pin] < amount){
cout << endl;
cout << "Insufficient Balance!" << endl;
return balance[pin];
}
}
balance[pin] -= amount;
return balance[pin];
}
...
double balances[N];
int pin;
...
withdrawAmount(pin, balances);
menuBoard();
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'm new to programing and I'm trying to get this program to add up a price of coffee to the add on extras such as cinnamon, etc. But once the program runs it doesn't add up the coffee price with the extras and I've been at it for hours and I'm stumped. Like I said I'm new to this so if someone can help and explain why its not working or what I need to fix that would be great. Thank you!
Code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
const int SIZE = 5;
double COFFEEPRICE = 2.00;
string products[SIZE]= {"Whipped cream", "Cinnamon", "Chocolate sauce", "Amaretto", "Irish whiskey"};
double prices[SIZE]={0.89, 0.25, 0.59, 1.50, 1.75};
int totalPrice = 0;
int choice = 0;
int SENTINEL = -1;
{
while (choice <= SENTINEL)
cout << "Please select an item from the Product menu by selecting the item number (1 - 5) or -1 to terminate: " ;
cout << "Product Price ($)" << endl;
cout << "======= =========" << endl;
cout << "1. Whipped cream 0.89" << endl;
cout << "2. Cinnamon 0.25" << endl;
cout << "3. Chocolate sauce 0.89" << endl;
cout << "4. Amaretto 1.50" << endl;
cout << "5. Irish whiskey 1.75" << endl;
cout << "Please enter a positive number: " << endl;
cin >> choice;
if (choice > SENTINEL)
{
if ((choice >= 1) && (choice <= 5))
{
totalPrice = totalPrice + prices[choice-1];
cout << "Item number " << choice << ": "<< products[choice-1] << " has been added" << endl;
}
else
{
cout << "Item number ",choice, " is not valid", "Sorry we do not carry that item" ;
}
}
totalPrice + COFFEEPRICE;
cout << "Total price of order is $" << totalPrice << endl;
cout << "Thanks for purchasing from Jumpin Jive Coffee Shop" << endl;
}
system("pause");
return 0;
}
You have to assign new price, which is
totalPrice + COFFEEPRICE
to the old value. So write:
totalPrice = totalPrice + COFFEEPRICE; // note,
// same as totalPrice += COFFEEPRICE;
Otherwise, the expression totalPrice + COFFEEPRICE; does nothing useful.
Also, I wonder how this work for you (this won't get into while(): probably just for debugging?):
int choice = 0;
int SENTINEL = -1;
{
while (choice <= SENTINEL)
You need to change
totalPrice + COFFEEPRICE; // Problem: totalPrice will not change!!!
to
totalPrice = totalPrice + COFFEEPRICE; // add and update by assign back
or
totalPrice += COFFEEPRICE; // equivalent to the above
in order to update totalPrice with the new added value.
Found too many error so instead of pointing each one...I have made changes and posted the correct code...
First and major one will be loop...
You havn't got any input from user and checking whether he wants to quit(by entering negative number)...way you have use while loop is not correct...
do while made more sense here....also total totalPrice + COFFEEPRICE; You need to store this value somewhere so that you can use it again
double totalPrice;
totalPrice = totalPrice + COFFEEPRICE;
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
const int SIZE = 5;
double COFFEEPRICE = 2.00;
string products[SIZE]= {"Whipped cream", "Cinnamon", "Chocolate sauce", "Amaretto", "Irish whiskey"};
double prices[SIZE]={0.89, 0.25, 0.59, 1.50, 1.75};
double totalPrice = 0;
int choice = 0;
int SENTINEL = -1;
do
{
cout << "Please select an item from the Product menu by selecting the item number (1 - 5) or -1 to terminate: " ;
cout << "Product Price ($)" << endl;
cout << "======= =========" << endl;
cout << "1. Whipped cream 0.89" << endl;
cout << "2. Cinnamon 0.25" << endl;
cout << "3. Chocolate sauce 0.89" << endl;
cout << "4. Amaretto 1.50" << endl;
cout << "5. Irish whiskey 1.75" << endl;
cout << "Please enter a positive number: " << endl;
cin >> choice;
if (choice > SENTINEL)
{
if ((choice >= 1) && (choice <= 5))
{
totalPrice = totalPrice + prices[choice-1];
cout << "Item number " << choice << ": "<< products[choice-1] << " has been added" << endl;
}
else
{
cout << "Item number ",choice, " is not valid", "Sorry we do not carry that item" ;
}
}
totalPrice = totalPrice + COFFEEPRICE;
cout << "Total price of order is $" << totalPrice << endl;
cout << "Thanks for purchasing from Jumpin Jive Coffee Shop" << endl;
}while (choice <= SENTINEL);
//system("pause");
return 0;
}