C++ - How to call variables from functions without using global variables - c++

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.

Related

how to add all in all the total in loop?

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.

How can I use arrays to ask my customers the quantity they want and print a receipt from the arrays?

I need to create arrays that save the quantity of the item the user selects and also prints out a receipt with the product, quantity and the total price. Please help me understand how to do this. I've got a basic understanding of what an array is. I just couldn't figure out how to save the users input.
#include <iostream>
#include <Windows.h>
#include <cstdlib>
#include <string>
#include "customerclass.h"
using namespace std;
//***** Functions to calculate the price of multiple items *****
void finalPrice1(int itemQuantity) {
float price;
price = itemQuantity * 3.00;
cout << "Your total is $" << price << endl;
cout << "Thank you for using my shop" << endl;
exit(0);
}
void finalPrice2(int itemQuantity) {
float price;
price = itemQuantity * 2.50;
cout << "Your total is $" << price << endl;
cout << "Thank you for using my shop" << endl;
exit(0);
}
void finalPrice3(int itemQuantity) {
float price;
price = itemQuantity * 1.25;
cout << "Your total is $" << price << endl;
cout << "Thank you for using my shop" << endl;
exit(0);
} //***** End of functions that calculate price of multiple items *****
int main(void)
{
char selection = ' ';
string lname = "";
string luserAddress;
int itemQuantity;
string orderFinalized;
CustomerInfo myCustomerInfo;
do
{ // Displaying menu
cout << "Hello, welcome to my online shop! What is your name? " << endl;
cin >> lname;
cout << " And what is your shipping address? " << endl;
cin >> luserAddress;
myCustomerInfo.setName(lname);
myCustomerInfo.setAddress(luserAddress);
cout << lname + ", nice to meet you. Here are the items in my shop followed by the price, please enter the number that corresponds to the item you want. \n " << endl;
cout << "Products \n";
cout << "1 - Chocolate candy bar - $3.00" << endl;
cout << "2 - Sour hard candy - $2.50" << endl;
cout << "3 - Mints - $1.25" << endl;
cout << "4 - Exit" << endl << endl;
cout << "Enter selection ";
// Reading User Selection
cin >> selection;
switch (selection)
{
case '1':
cout << "You've chosen a Chocolate candy bar. How many would you like? ";
cin >> itemQuantity;
cout << "Ok, will this finalize your order? Type and enter either 'Yes' or 'No' " << endl;
cin >> orderFinalized;
if (orderFinalized == "Yes" || orderFinalized == "yes" || orderFinalized == "YES") {
cout << myCustomerInfo.getName() + " your items will be shipped to " << myCustomerInfo.getAddress() << endl;
cout << "Printing your receipt now..." << endl;
finalPrice1(itemQuantity);
}
break;
case '2':
cout << "You've chosen Sour hard candy. How many would you like? ";
cin >> itemQuantity;
cout << "Ok, will this finalize your order? Type and enter either 'Yes' or 'No' " << endl;
cin >> orderFinalized;
if (orderFinalized == "Yes" || orderFinalized == "yes" || orderFinalized == "YES") {
cout << myCustomerInfo.getName() + " your items will be shipped to " << myCustomerInfo.getAddress() << endl;
cout << "Printing your receipt now..." << endl;
finalPrice2(itemQuantity);
}
break;
case '3':
cout << "You've chosen Mints. How many would you like? ";
cin >> itemQuantity;
cout << "Ok, will this finalize your order? Type and enter either 'Yes' or 'No' " << endl;
cin >> orderFinalized;
if (orderFinalized == "Yes" || "yes" || "YES") {
cout << myCustomerInfo.getName() + " your items will be shipped to " << myCustomerInfo.getAddress() << endl;
cout << "Printing your receipt now..." << endl;
finalPrice3(itemQuantity);
}
break;
case '4':
cout << "Thank you for using my shop. <exiting now...>" << endl;
break;
default: cout << "Invalid selection. Please try again";
}
cout << endl << endl;
} while (selection != '4');
return 0;
}
You need dynamic array. For example:
cin >> itemQuantity;
// create a array during runtime
// and the size is itemQuantity
// you can access the ith array element by items[i]
Item *items= new Item[itemQuantity];
Or you can use the vector,
vector<Item> items;//you can also access the ith element by items[i]
items.push_back(hard_candy);//items = {hard_candy}
items.push_back(soft_candy);//items = {hard_candy, soft_candy}
items.pop_back();//items = {hard_candy}
BTW, the case 3 in your code has some error:
orderFinalized == "Yes" || "yes" || "YES"//wrong
orderFinalized == "Yes" || orderFinalized == "yes" || orderFinalized == "YES"//right

error expected expression on do while loop c++

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;
}

Passing array to Boolean Function

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.";
}
}

Serendipity booksellers software program C++

this is a project I'm working on which comes from the book I'm using to learn C++ - "Starting out with C++". I'm having a problem with the cashier portion of the project at the moment. It asks the user to enter the date, quantity, isbn, title, and price of the book. Then, it asks the user if they wish to enter another book. Regardless of whether they type "y" or "n" it continues to the next part of the program. I don't really know why the for loop doesn't repeat after I type "y" to enter another book. Also, the date is coming out with garbage at the end when it is displayed, that's another thing I need to fix. Any help would be appreciated. There is definitely more problems but the main problem is in the cashier function in the first for loop. I didn't include the whole program because it's very long.
/*
* mainmenu.cpp
* Serendipity Booksellers software
*
* Created by Abraham Quilca on 9/5/12.
* Copyright 2012 __MyCompanyName__. All rights reserved.
*
*/
#include<iostream>
#include<iomanip>
#include<cstring>
#include"mainmenu.h"
using namespace std;
char bookTitle[20][51],
isbn[20][14],
author[20][31],
publisher[20][31],
dateAdded[20][11];
int qtyOnHand[20];
double wholesale[20];
double retail[20];;
int main()
{
int choice;
do
{
cout << "\t\t Serendipity Booksellers"<< endl;
cout << "\t\t\t Main Menu" << endl << endl;
cout << "\t\t1. Cashier Module" << endl;
cout << "\t\t2. Inventory Database Module" << endl;
cout << "\t\t3. Report Module" << endl;
cout << "\t\t4. Exit" << endl << endl;
cout << "\t\tEnter your choice: ";
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
cashier();
break;
case 2:
invmenu();
break;
case 3:
reports();
break;
case 4:
continue;
break;
default:
cout << "\t\tPlease enter a number in the range 1-4." << endl << endl;
}
}
while(choice != 4);
cout << "\t\tYou selected item 4." << endl;
return 0;
}
// Cashier function
void cashier()
{
char again;
char date[8];
int quantity[20] = {0};
char ISBN[20][20] = {0};
char title[20][40] = {0};
float price[20] = {0}, bookTotal[20] = {0}, subtotal, total, tax;
const float tax_rate = .06;
cout << "Serendipity Booksellers" << endl;
cout << " Cashier Module" << endl << endl;
for(int count = 0; count < 20; count++)
{
cout << "Date: ";
cin >> date;
cout << "Quantity of Book: ";
cin >> quantity[count];
cout << "ISBN: ";
cin >> ISBN[count];
cout << "Title: ";
cin.ignore();
cin.getline(title[count], 40);
cout << "Price: ";
cin >> price[count];
bookTotal[count] = quantity[count] * price[count];
subtotal += price[count];
cout << "Would you like to enter another book? (Y/N) ";
cin >> again;
if(again == 'N' || 'n')
count = 21; // This line will end the for loop
}
// Calculating tax and total
tax = subtotal * tax_rate;
total = subtotal + tax;
cout << "\n\nSerendipity Booksellers" << endl << endl;
cout << "Date:" << date << endl << endl;
cout << "Qty\t ISBN\t\t "
<< left << setw(40) << "Title" << "Price\t Total" << endl
<< "-------------------------------------------------------------------------------"
<< endl << endl;
for(int count = 0; count < 20; count++)
{
cout << quantity[count] << "\t " << ISBN[count] << " " << left << setw(40) << title[count]
<< setprecision(2) << fixed << "$" << setw(6) << price[count] << " $" << setw(6) << bookTotal[count]
<< endl << endl;
}
cout << "\t\t\t Subtotal" << "\t\t\t\t $" << setw(6) << subtotal << endl;
cout << "\t\t\t Tax" << "\t\t\t\t $" << setw(6) << tax<< endl;
cout << "\t\t\t Total" "\t\t\t\t $" << setw(6) << total << endl << endl;
cout << "Thank You for Shopping at Serendipity!" << endl << endl;
}
if(again == 'N' || 'n')
This doesn't do what you think it does. Look at it like this:
if((again == 'N') || ('n'))
Is again == N true OR is n true? Well n will always be true (it is a char with non-zero value) so your loop will always end immediately. What you want is:
if(again == 'N' || again == 'n')
Also, you can break out of a loop using the aptly named break keyword:
if (again == 'N' || again == 'n') {
break;
}
The problem with the loop is this line:
if(again == 'N' || 'n')
C++ doesn't know that you mean it to check again against both characters. Instead, it tries again == 'N', which fails, and then tries 'n', which - not being zero - evaluates as true.
Instead, try:
if (again == 'N' || again == 'n')
break;