I am not done with my code yet but so far I have a error, all the way in the bottom where I am trying to do my do while statement the first line
cout << "Please enter one of the following: \n"; says expected expression so it is not letting me run the code, help please?
#include <iostream>
using namespace std;
int main() {
int numTickets, options, count = 0;
double total, discount, costTicket = 10, discountPrice = .05;
char member;
cout << ":)\t Welcome to the Regal Entertainment Group Theater\t :)\n"
<< ":)\t ****The greatest movie theater in the world.****\t :)\n\n";
cout << "Please enter one of the following: \n";
cout << "1 - I want tickets to watch the movie!\n"
<< "2 - I'm out.\n";
cin >> options;
cout << "How many tickets will you need to watch your movie tonight? ";
cin >> numTickets;
cout << "Are you a member of our marvelous Regal Crown Club (Y/N)? ";
cin >> member;
if(numTickets <= 0)
cout << "Please enter a number greater than 0.";
else if(numTickets < 4)
costTicket = 10;
else if(numTickets >= 5)
costTicket = 8;
if(member == 'Y' || member == 'y')
{
discount = costTicket * numTickets * discountPrice;
total = numTickets * costTicket - discount;
cout << "Your total for the movie tickets is going to be: ";
cout << "$" << total << endl;
cout << "You saved $" << discount << endl;
cout << "You can pick up your free small popcorn at the stand.\n";
cout << "Thanks for coming to watch your movie at Regal Entertainment Group!\n";
}
else
{
total = numTickets * costTicket;
cout << "Your total for the movie tickets is going to be: ";
cout << "$" << total << endl;
cout << "Thanks for coming to watch your movie at Regal Entertainment Group!\n";
}
system("cls");
do
{
cout << "Please enter one of the following: \n";
cout << "1 - I want tickets to watch the movie!\n";
cout << "2 - I'm out.\n";
cin >> options;
}while(options != 2);
return 0;
}
Related
I get an error of "no operator matches these operands" when using the part of the code outputFile << customerName << "your Monthly payments are " << monthlyPay << endl;. Overall, I need the code to Add the ability to save data to disk in one or more files and a menu should give the user the option to save or retrieve data. I have not gotten past the error to properly run the program. Can you please help fix error.
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <vector>
#include<fstream>
using namespace std;
void menu(void);
void writeData(void);
void readData(void);
const char FileName[] = "CourseProjectAvilaF.txt";
//Variables
vector <double> Loanlgth, Loanamt, interestRate, totalInterest;
vector <double> monthlyPay(100), loanTotal(100), creditScore(100);
vector <string> customerName;
int main()
{
menu();
return 0;
}
void menu(void)
{
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
int option;
//Program
cout << "Thank you for choosing The Bank of UA for your loan requirements!\n\n";
do
{
cout << "UA Bank menu:\n\n"
<< "1. Enter your information\n"
<< "2. See your loan requirements\n"
<< "3. Exit program\n\n"
<< "Choose an option: ";
cin >> option;
while (option < INPUT_CUSTOMER || option > EXIT_PROGRAM)
{
cout << "Please enter a valid menu option: ";
cin >> option;
}
if (option == 1)
{
writeData();
}
if (option == 2)
{
readData();
}
} while (option != EXIT_PROGRAM);
}
//function to read customer information
void writeData(void)
{
fstream outputFile;
outputFile.open(FileName, fstream::app);
int index;
int numCustomers = 0;
cout << "Please enter the number of customers you would like\n"
<< " to enter loan information for: ";
cin >> numCustomers;
for (index = 0; index < numCustomers; index++)
{
string tempName;
double tempLoanamt, tempLoanlgth, tempcreditScore, tempinterestRate,
tempinterest;
cout << "Please enter your name: ";
cin >> tempName;
customerName.push_back(tempName);
cout << "Please enter the loan amount: $";
cin >> tempLoanamt;
Loanamt.push_back(tempLoanamt);
cout << "Please enter the length of the loan in months: ";
cin >> tempLoanlgth;
Loanlgth.push_back(tempLoanlgth);
cout << "What is your current credit score? ";
cin >> tempcreditScore;
creditScore.push_back(tempcreditScore);
//This will determine interest rate and overall loan amount when calculated
if (tempcreditScore <= 650)
tempinterestRate = .12;
else
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
//Calculations
tempinterest = Loanamt[index] * interestRate[index];
totalInterest.push_back(tempinterest);
loanTotal[index] = (Loanamt[index] + totalInterest[index]);
monthlyPay[index] = loanTotal[index] / Loanlgth[index];
// Out put files to write data to be saved
outputFile << customerName << "your Monthly payments are " << monthlyPay << endl;
outputFile << "Your total interest is " << totalInterest << endl;
outputFile << "You owe " << loanTotal << endl;
outputFile << "You have " << Loanlgth << " months to pay off your balance" << endl;
}
outputFile.close(); //Close file
}
//function loan information
void readData(void)
{
int index;
int numCustomers = 0;
ifstream inputFile;
inputFile.open(FileName, fstream::in);//Open the file with read mode
//Display monthly payment
cout << fixed << setprecision(2);
for (index = 0; index < numCustomers; index++)
{
cout << customerName[index] << " your total loan is " << loanTotal[index]
<< "\n"
<< "with a monthly payment of $" << monthlyPay[index] << "\n"
<< "for " << Loanlgth[index] << " months with an interest\n"
<< "rate of " << interestRate[index] << endl;
}
}
It's simple enough, you got it right everywhere else in your program.
When you want to access a particular element of a vector you use an index. Like this
outputFile << customerName[index] << "your Monthly payments are " << monthlyPay[index] << endl;
outputFile << "Your total interest is " << totalInterest[index] << endl;
outputFile << "You owe " << loanTotal[index] << endl;
outputFile << "You have " << Loanlgth[index] << " months to pay off your balance" << endl;
customerName and monthlyPay are vectors. You can't stream them directly. Instead you can do something like
for (auto const &name : customerName)
outputFile << name;
It is me again. I want to add the prices in the purchase if I want to buy more items. But I do not know how to do that. For example if, I confirm my purchase and want to buy more items, I want it to add the prices that is confirmed to purchase, and if I finally do not want to buy more items and not to look for more items, that total price would be computed.
int main()
{
int choice;
int purchase;
int quantity;
double totalChoice1;
double totalChoice2;
char view;
char confirm;
char buyMore;
char look;
double alloy, apex, kraken, aorus;
double oppo, alpha, rog, huawei;
double ps4, nintendo, xbox, wii;
alloy = 69.99;
apex = 199;
kraken = 90;
aorus = 60;
do {
cout << "What type of items would you like to view?" << endl;
cout << " [1] Peripherals" << endl;
cout << " [2] Mobile Phones" << endl;
cout << " [3] Consoles" << endl;
cout << " [4] Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
if (choice == 1) {
cout << "--------------------" << endl;
cout << "What peripherals would you like to purchase?" << endl;
cout << "[1] HyperX Alloy FPS PRO - $69.99" << endl;
cout << "[2] SteelSeries APEX PRO - $199" << endl;
cout << "[3] Razer Kraken X - $90" << endl;
cout << "[4] AORUS K7 - $60" << endl;
cout << "[5] BACK TO MENU" << endl;
cout << "Enter your choice: ";
cin >> purchase;
cout << "--------------------" << endl;
if (purchase == 1) {
cout << "How many would you like to purchase? ";
cin >> quantity;
totalChoice1 = quantity * alloy;
cout << "The total price for that is " << totalChoice1 << endl;
cout << "Confirm the Purchase? [Y]/[N]: ";
cin >> confirm;
if (confirm == 'Y') {
totalChoice1; // This is just a trial code.
cout << "Would you like to buy more items? [Y]/[N]: ";
cin >> buyMore;
}
else if (confirm == 'N') {
cout << "Do you still want to look for items? [Y]/[N]: ";
cin >> look;
if (look == 'N') {
break;
}
}
else {
break;
}
}
}
while (purchase == 5 || buyMore == 'Y' || look == 'Y');
cout << "The total price for your items is: " << totalChoice1; // This is also a trial code (totalChoice1)
}
You are simply missing a variable to keep track of that total. Don't forget to give it an initial value of 0!
There are plenty of minor other issues with your code, so you'll have some more learning ahead. For instance, we find it easier to do bookkeeping in cents, because you can treat them as integers.
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've been trying to complete a task but I am not allowed to use global variables.
The task if that you have to make a coffee shop program where user can buy coffee (small, medium or large), then show the total number of coffee cups sold and then then total sales made from selling coffee. I completed half of the code where user can buy but I am stuck at summing coffee sales/cups.
The function cupsSold and totalAmount return 0 or garbage value. Also I am not allowed to use extra library functions.
Is there any way to call variables from another function without using global variables?
This is my main code:
#include <iostream>
using namespace std;
void showChoices()
{
cout << "Welcome to Jason's Coffee Shop\n\n";
cout << "1. Buy Coffee" << endl;
cout << "2. Show total cups sold by size"<< endl;
cout << "3. Show total amount of coffee sold"<<endl;
cout << "4. Show total amount of money made"<< endl;
cout << "0. Exit" << endl;
cout << "\nYour choice: ";
}
void buyCoffee(int numberSmCups,float totalSmCups,int numberMedCups,float totalMedCups, int numberLgCups,float totalLgCups)
{
char coffeeSize, order = 'y';
bool coffeeSelect = true;
float smCoffee = 1.75, mdCoffee = 1.90, lgCoffee = 2.00, totalCoffee = 0;
while(coffeeSelect)
{
if (order == 'y' ||order =='Y'){
cout << "Size of Coffee [S, M, L]: ";
cin >> coffeeSize;
if (coffeeSize == 's' || coffeeSize == 'S')
{
cout << "Quantity of Small Coffee: ";
cin >> numberSmCups;
totalSmCups = numberSmCups * smCoffee;
cout << "Small Coffee: "<<numberSmCups<<", Bill: "<<totalSmCups<<endl;
totalCoffee += totalSmCups;
cout << "Add another coffee [Y or N]: "<<endl;
cin >> order;
}
else if (coffeeSize == 'm' || coffeeSize == 'M')
{
cout << "Quantity of Medium Coffee: ";
cin >> numberMedCups;
totalMedCups = numberMedCups * mdCoffee;
cout << "Medium Coffee: "<<numberMedCups<<", Bill: "<<totalMedCups<<endl;
totalCoffee += totalMedCups;
cout << "Add another coffee [Y or N]: "<<endl;
cin >> order;
}
else if (coffeeSize == 'l' || coffeeSize == 'L')
{
cout << "Quantity of Large Coffee: ";
cin >> numberLgCups;
totalLgCups = numberLgCups * lgCoffee;
cout << "Large Coffee: "<<numberLgCups<<", Bill: "<<totalLgCups<<endl;
totalCoffee += totalLgCups;
cout << "Add another coffee [Y or N]: ";
cin >> order;
}
}
else
break;
}
cout << "--------------\n";
cout << "Your invoice: "<<endl;
cout<< endl;
if (numberSmCups>= 1)
cout << "Small Coffee: "<< numberSmCups <<" cups ($ "<< smCoffee <<"/cup) Amount: $ "<< totalSmCups << endl;
if (numberMedCups>=1)
cout << "Medium Coffee: "<< numberMedCups <<" cups ($ "<< mdCoffee << "/cup) Amount: $ "<< totalMedCups << endl;
if (numberLgCups>=1)
cout << "Large Coffee: " << numberLgCups <<" cups ($ " << lgCoffee << "/cup) Amount: $ " << totalLgCups << endl;
cout<< endl;
cout << "Total Amount: "<<"$ "<< (totalSmCups+ totalMedCups+ totalLgCups) << endl;
cout << "--------------" << endl;
}
void cupsSold(int numberSmCups,int numberMedCups,int numberLgCups){
int lifeSmCups=0;
int lifeMdCups=0;
int lifeLgCups=0;
lifeSmCups = lifeSmCups + numberSmCups;
lifeMdCups = lifeMdCups + numberMedCups;
lifeLgCups = lifeLgCups + numberLgCups;
cout << "Total Small cups: "<<lifeSmCups<<endl;
cout << "Total Medium Cups:"<<lifeMdCups<<endl;
cout << "Total Large Cups:"<<lifeLgCups<<endl;
}
void totalAmount(float totalCoffee)
{
cout << "Total: "<<"$"<<totalCoffee<<endl;
}
int main()
{
int numberSmCups = 0, numberMedCups = 0, numberLgCups = 0, choice;
float totalSmCups = 0, totalMedCups = 0, totalLgCups = 0, totalCoffee;
while (choice != 0)
{
showChoices();
cin >> choice;
cout << endl;
if (choice == 1)
{
cout <<"You selected to buy coffee."<< endl;
buyCoffee(numberSmCups,totalSmCups,numberMedCups,totalMedCups,numberLgCups,totalLgCups);
}
else if (choice == 2)
{
cout << "The total amount of cups sold by size is: "<<endl;
cupsSold(numberSmCups,numberMedCups,numberLgCups);
}
else if (choice == 3)
{
cout << "Total Coffee Sold: "<<endl;
// cupsSold(numberSmCups,numberMedCups,numberLgCups);
}
else if (choice == 4)
{
cout << "Money made from coffee sales: "<<endl;
totalAmount(totalCoffee);
}
else if (choice == 0)
{
cout << "EXIT"<<endl;
break;
}
else
cout << "Invalid Input" << endl;
}
return 0;
}
"Is there any way to call variables from another function without using global variables?"
You need to use by reference parameters, if you want to change the variables passed to a function like this
void cupsSold(int& numberSmCups,int& numberMedCups,int& numberLgCups){
// ^ ^ ^
otherwise these functions just operate on copies rather than your original variable values.
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.";
}
}