Billing System Total has an output of 0 [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am a first-year college student and I am currently having trouble with this program I am working on, It is about a billing system. I managed to do everything but the final part, which is printing the total, tax, and the final bill. Anything I try to do either gives me a wrong answer or a 0. Please help.
#include <iostream>
#include <string.h>
#include <iomanip>
#define MAX 8
using namespace std;
struct menuItemType{
string menuItem;
double menuPrice;
};
menuItemType menulist[MAX];
void getData();
void showMenu();
int printCheck(void);
//int b[8] = {0,0,0,0,0,0,0,0};
int main(){
cout << "Welcome to Mavel's Restaurant\n\n";
cout << "------------ Menu ------------ \n";
showMenu();
getData();
int choice;
char add;
do {
cout << "Enter choice: ";
cin >> choice;
switch (choice){
case 1:
cout<< "You ordered Plain Egg.\n";
break;
case 2:
cout<< "You ordered Bacon and Egg.\n";
break;
case 3:
cout<< "You ordered a muffin.\n";
break;
case 4:
cout<< "You ordered French Toast.\n";
break;
case 5:
cout<< "You ordered Fruit Basket.\n";
break;
case 6:
cout<< "You ordered Cereal.\n";
break;
case 7:
cout<< "You ordered Coffee.\n";
break;
case 8:
cout<< "You ordered Tea.\n";
break;
default:
cout<< "Invalid Choice.";
break;
}
cout<< "Would you like to order another item? [Y]es / [N]o : ";
cin >> add;
if (add == 'N'||add =='n'){
printCheck();
}
}
while (add == 'Y'|| add == 'y');
}
void getData(){
menulist[0].menuItem = "Plain Egg";
menulist[0].menuPrice = 140.50;
menulist[1].menuItem = "Bacon and Egg";
menulist[1].menuPrice = 245.00;
menulist[2].menuItem = "Muffin";
menulist[2].menuPrice= 295.00;
menulist[3].menuItem = "French Toast";
menulist[3].menuPrice = 495.00;
menulist[4].menuItem = "Fruit Basket";
menulist[4].menuPrice = 555.00;
menulist[5].menuItem = "Cereal";
menulist[5].menuPrice = 385.00;
menulist[6].menuItem = "Coffee";
menulist[6].menuPrice = 415.00;
menulist[7].menuItem = "Tea";
menulist[7].menuPrice = 333.00;
}
void showMenu(){
cout << "[1] Plain Egg\t\tPhp140.50\n";
cout << "[2] Bacon and Egg\tPhp245.00\n";
cout << "[3] Muffin\t\tPhp295.00\n";
cout << "[4] French Toast\tPhp495.00\n";
cout << "[5] Fruit Basket\tPhp555.00\n";
cout << "[6] Cereal\t\tPhp385.00\n";
cout << "[7] Coffee\t\tPhp415.00\n";
cout << "[8] Tea\t\t\tPhp333.00\n\n";
}
double total = 0;
int printCheck(){
getData();
double total = 0 , tax, totalbill;
for (int i = 0; i < 8; i++){
total += menulist[i].menuPrice;
}
tax = total * 0.05;
totalbill = total+tax;
cout << "----------------------------------------------\n";
cout << "Tax\t\t" << tax<< endl;
cout << "Amount Due\tPhp" << totalbill << endl;
cout << "----------------------------------------------\n";
return total;
}

Your code is a bit all over the place, with some small reorganization you can get the intended result, here is a possible fix, with comments where needed:
Live sample
#include <iostream>
#include <string.h>
#include <iomanip>
#define MAX 8
using namespace std; // I would avoid using namespace std, explanation ahead
struct menuItemType
{
string menuItem;
double menuPrice;
};
//menuItemType menulist[MAX]; //does not need to be global
void getData(menuItemType *menulist);
void showMenu();
int printCheck(double total); // pass the total to the printCheck() function
int main()
{
menuItemType menulist[MAX]; // go local when possible
cout << "Welcome to Mavel's Restaurant\n\n";
cout << "------------ Menu ------------ \n";
showMenu(); // here you could also pass menulist and print the menu using the data
//it would be easier to refactor if you add a menu item, try it
getData(menulist);
int choice;
char add;
double total = 0;
do
{
cout << "Enter choice: ";
cin >> choice;
// do the math in the cycle so you can keep track of the sum of selected items
if(choice > 0 && choice <= MAX)
total += menulist[choice - 1].menuPrice;
switch (choice) // if you want to separate logic from UI, this could
// be a separate function, i.e. printChoice(choice);
{
case 1:
cout << "You ordered Plain Egg.\n";
break;
case 2:
cout << "You ordered Bacon and Egg.\n";
break;
case 3:
cout << "You ordered a muffin.\n";
break;
case 4:
cout << "You ordered French Toast.\n";
break;
case 5:
cout << "You ordered Fruit Basket.\n";
break;
case 6:
cout << "You ordered Cereal.\n";
break;
case 7:
cout << "You ordered Coffee.\n";
break;
case 8:
cout << "You ordered Tea.\n";
break;
default:
cout << "Invalid Choice.";
break;
}
cout << "Would you like to order another item? [Y]es / [N]o : ";
cin >> add;
if (add == 'N' || add == 'n') // this condition is also refactorable, you could
// simply move the print to after the loop ends
{
printCheck(total);
}
} while (add == 'Y' || add == 'y');
//printCheck(total); //here
}
void getData(menuItemType *menulist)
{
menulist[0].menuItem = "Plain Egg";
menulist[0].menuPrice = 140.50;
menulist[1].menuItem = "Bacon and Egg";
menulist[1].menuPrice = 245.00;
menulist[2].menuItem = "Muffin";
menulist[2].menuPrice = 295.00;
menulist[3].menuItem = "French Toast";
menulist[3].menuPrice = 495.00;
menulist[4].menuItem = "Fruit Basket";
menulist[4].menuPrice = 555.00;
menulist[5].menuItem = "Cereal";
menulist[5].menuPrice = 385.00;
menulist[6].menuItem = "Coffee";
menulist[6].menuPrice = 415.00;
menulist[7].menuItem = "Tea";
menulist[7].menuPrice = 333.00;
}
void showMenu()
{
cout << "[1] Plain Egg\t\tPhp140.50\n";
cout << "[2] Bacon and Egg\tPhp245.00\n";
cout << "[3] Muffin\t\tPhp295.00\n";
cout << "[4] French Toast\tPhp495.00\n";
cout << "[5] Fruit Basket\tPhp555.00\n";
cout << "[6] Cereal\t\tPhp385.00\n";
cout << "[7] Coffee\t\tPhp415.00\n";
cout << "[8] Tea\t\t\tPhp333.00\n\n";
}
// now can simply print the check
int printCheck(double total)
{
double tax = total * 0.05;
double totalbill = total + tax;
cout << "----------------------------------------------\n";
cout << "Tax\t\t" << tax << endl;
cout << "Amount Due\tPhp" << totalbill << endl;
cout << "----------------------------------------------\n";
return total; // you're not using this return value, you may aswell make the function return type void
}
For more information whether you should use using namespace std; check this link:
Why is "using namespace std;" considered bad practice?
Note that the code still have some weaknesses, namely the lack of input validation, if, as an example, your input is not a number when you are prompted to give a choice you have a problem. If you want to learn more about this there are many threads in SO you can find, for instance:
Good input validation loop using cin - C++

Related

How to create a program that can overwrite a pre-initialized variable with user inputted data during runtime?

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?

Replace if else with Switch statement

I am working on the code below and trying to use switch statement instead of if/else.
The problem is that I cannot figure out how to get the switch to work.
A few things a tried:
I know that every time an expression is equal to the case constant, the code then will be executed. Example:
switch (expression)
{
case 1:
// code to be executed if
// expression is equal to 1;
break;
}
My code below has a similar concept, but I cannot get it display the calculation. There are no errors, but it does not display the total price.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
const int CHEESE_PIZZA = 11;
const int SPINACH_PIZZA = 13;
const int CHICKEN_PIZZA = 14;
cout << " *********** MENU ***********" << endl;
cout << setw (9) << "ITEM" << setw (20) << "PRICE" << endl;
cout << " (1) Cheese Pizza" << setw (8) << "$"
<< CHEESE_PIZZA << endl;
cout << " (2) Spinach Pizza" << setw (7) << "$"
<< SPINACH_PIZZA << endl;
cout << " (3) Chicken Pizza" << setw (7) << "$"
<< CHICKEN_PIZZA << endl;
cout << endl;
cout << "What would you like? ";
int option;
cin >> option;
cout << "You picked pizza option " << option << endl;
cout << "How many orders? ";
int quantity;
cin >> quantity;
cout << "You choose quantity " << quantity << endl;
int price;
switch (option)
{
case 1:
price = CHEESE_PIZZA;
break;
case 2:
price = SPINACH_PIZZA;
break;
case 3:
price = CHICKEN_PIZZA;
break;
default:
cout << "Please select valid item from menu. " << endl;
}
return 1;
int amount = price * quantity;
cout << "Your Bill: $ " << amount << endl;
cout << endl;
return 0;
}
I am confused about the output for any input other than 1, 2, and 3 in case 4.
The if/else statement works:
int price;
if (option == 1) price = CHEESE_PIZZA;
else if (option == 2) price = SPINACH_PIZZA;
else if (option == 3) price = CHICKEN_PIZZA;
else {
cout << "Please select valid item from menu. " << endl;
return 1;
}
The problem, from eyeballing, appears to be because you return 1 outside the switch statement, which is why the code after it never gets run.
You should replace your case 4 with a default: label and move the return 1; into that case as well as add a break statement under case 3.

Variable always resets to default in Functions

I am building an ATM sort of program where you can deposit and withdraw balance with the use of functions. I noticed at first that after i deposit first time, it works fine but after the second time using deposit it doesn't add it to the current balance but the balance before it.
For example:
(1st Attempt)
*Balance = 1000
*I deposit 500
*Balance is now = 1500
(2nd Attempt)
*I deposit 700
*Balance is now 1700
Instead of making it to 2200, it resets back to 1000 before went for my second attempt resulting in a result of 1700.
Can anyone please explain what went wrong in the code? I am willing to not only get the correct code but to also learn how it was done.
This is for my training in c++.
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int deposit(int x, int y)
{
int newbal = x + y;
return newbal;
}
int withdraw(int x, int y)
{
int newbal = x - y;
return newbal;
}
int main()
{
int menu;
int selection;
double x = 1000, y;
int trans;
char user[20], pass[20], pktc[3];
string newuser, newpass;
do{
system ("CLS");
cout << "Welcome To Bank" << endl;
cout << "[1] Register" << endl;
cout << "[2] Login" << endl;
cout << "[3] Exit" << endl;
cout << "\n\nEnter command: " <<endl;
cin >> menu;
switch(menu)
{
//----------------------------------------------------------------CASE 1------------------------------------------------------------------------------//
//----------------------------------------------------------------REGISTER----------------------------------------------------------------------------//
case 1:
system ("CLS");
cout << "<-------REGISTER------->\n\n";
cout << "Enter Name: ";
cin >> user;
newuser = user;
cout << "Enter Password: ";
cin >> pass;
newpass = pass;
cout <<"REGISTERED SUCCESSFULLY!" << endl;
cout <<"\n\nPress Any key to contniue" << endl;
cin >> pktc;
system ("CLS");
break;
//------------------------------------------------------------END OF REGISTER--------------------------------------------------------------------------//
//----------------------------------------------------------------CASE 2------------------------------------------------------------------------------//
//-----------------------------------------------------------------LOGIN------------------------------------------------------------------------------//
case 2:
system ("CLS");
cout << "<-------LOGIN------->\n\n";
cout << "Enter Username: ";
cin >> newuser;
cout << "Enter Password: ";
cin >> newpass;
if(newuser != user || newpass != pass)
{
//-------------------------------------------------------------FAILED LOGIN----------------------------------------------------------------------------//
cout << "\nInvalid account" << endl;
cout <<"\n\nPress Any key to contniue" << endl;
cin >> pktc;
system ("CLS");
}
else if (newuser == user || newpass == pass)
{
//----------------------------------------------------------------CASE 2.1------------------------------------------------------------------------------//
//------------------------------------------------------------SUCCESFULL LOGIN--------------------------------------------------------------------------//
system ("CLS");
cout << "\n\n<-------------------------------WELCOME------------------------------->\n\n" << endl;
cout<<"\nWelcome To Banco De Nelio";
cout<<"\nUSERNAME: "<< user << endl;
cout<<"\n\n TIP ATM MACHINE";
cout<<"\n 1. Balance";
cout<<"\n 2. Deposit";
cout<<"\n 3. Withdraw";
cout<<"\n 4. Exit";
do{
cout<<"\n\nChoose Transaction[1-3]:";
cin>>trans;
switch(trans)
{
//----------------------------------------------------------------ATM CASE 1------------------------------------------------------------------------------//
//--------------------------------------------------------------CHECK BALANCE--------------------------------------------------------------------------//
case 1:
system ("CLS");
cout << "\n\n<-------------------------------WELCOME------------------------------->\n\n" << endl;
cout<<"\nWelcome To Banco De Nelio";
cout<<"\nUSERNAME: "<< user << endl;
cout<<"\n\n TIP ATM MACHINE";
cout<<"\n 1. Balance";
cout<<"\n 2. Deposit";
cout<<"\n 3. Withdraw";
cout<<"\n 4. Exit";
cout<<"\n\nYour total balance is: "<< deposit(x, y) ;
break;
//----------------------------------------------------------------ATM CASE 2------------------------------------------------------------------------------//
//--------------------------------------------------------------BEFORE DEPOSIT--------------------------------------------------------------------------//
case 2:
system ("CLS");
cout << "\n\n<-------------------------------WELCOME------------------------------->\n\n" << endl;
cout<<"\nWelcome To Banco De Nelio";
cout<<"\nUSERNAME: "<< user << endl;
cout<<"\n\n TIP ATM MACHINE";
cout<<"\n 1. Balance";
cout<<"\n 2. Deposit";
cout<<"\n 3. Withdraw";
cout<<"\n 4. Exit";
cout<<"\n\nEnter the amount:" ;
cin>>y;
//--------------------------------------------------------------AFTER DEPOSIT--------------------------------------------------------------------------//
system ("CLS");
cout << "\n\n<-------------------------------WELCOME------------------------------->\n\n" << endl;
cout<<"\nWelcome To Banco De Nelio";
cout<<"\nUSERNAME: "<< user << endl;
cout<<"\n\n TIP ATM MACHINE";
cout<<"\n 1. Balance";
cout<<"\n 2. Deposit";
cout<<"\n 3. Withdraw";
cout<<"\n 4. Exit";
cout<<"\n\nYour total balance now is: " << deposit(x, y) <<endl;
break;
//----------------------------------------------------------------ATM CASE 3------------------------------------------------------------------------------//
//--------------------------------------------------------------WITHDRAW BALANCE--------------------------------------------------------------------------//
case 3:
cout<<"\nEnter the amount:" ;
cin>>y;
if ( y > x)
{
cout<<"\nYou cannot withdraw " << y;
cout<<" because the amount is higher than your balance" << endl;
break;
}
else
x = x - y;
cout<<"\nYour Total Balance is now " << withdraw(x, y) << endl;
break;
//----------------------------------------------------------------ATM CASE 4------------------------------------------------------------------------------//
//-------------------------------------------------------------------BACK--------------------------------------------------------------------------------//
case 4:
cout<<"\n\nThank You!" << endl;
break;
default:
cout<<"\nYou did not enter any valid number" << endl;
break;
}
}while (trans<=3);
}
break;
//----------------------------------------------------------------CASE 3------------------------------------------------------------------------------//
//-----------------------------------------------------------------EXIT-------------------------------------------------------------------------------//
case 3:
system ("CLS");
cout << "Thank you for using me!\n";
return 0;
//-------------------------------------------------------------END OF EXIT----------------------------------------------------------------------------//
}
}while (menu<=3);
}
i am not sure if the problem here is the function or a conflict in switch statement.
Thanks In Advance
EDIT Please register first :)
Its really hard to spot the important pieces, but basically your problem can be boiled down to something like
int add(int x,int y) { return a+b; }
int sub(int x,int y) { return a-b; }
int main() {
int initial = 0;
// add 10 then subtract 5
std::cout << add(initial,10) << '\n'; // prints 10
std::cout << sub(initial,5) << '\n'; // prints -5
}
When what you actually want is something like
int main() {
int initial = 0;
// add 10 then subtract 5 and update initial
initial = add(initial,10);
std::cout << initial << '\n';
initial = sub(initial,5);
std::cout << initial << '\n';
}
Your methods correctly calculates the new amount, but when you call those methods you ignore the return value when instead you want to update some variable.
Some other suggestions (in random order):
use meaningful names. x and y do not convey any meaning, compare int deposit(int current_balance, int amount) to int deposit(int x,int y)
use functions to split your code into smaller pieces (eg it would be a good idea to seperate input, output and logic). Whenever you find yourself writing a comment describing what a block of code is doing, this block of code is a good candidate for a function that gets a proper name instead of a comment
dont use std::endl when you want to end a line (std::endl ends the line and flushes the stream, which is most of the time not what you want), use \n instead
dont use using namespace std;. It wont do much harm in your current code, but read here why you never should do it in a header, and better dont get used to bad habits from the start.

UI for Setting up a Checking account and Savings account for my bank project

I want to display an interface asking the user whether or not they want to use checkings or savings account, and then when they choose bring them to my generic display menu. But I'm not quite sure how to set it up. I was told to make Account objects and use a pointer, but as you can see I'm stuck. If anyone could give me any insight on how I would do this, I would greatly appreciate it.
Here is my code:
#ifndef ACCOUNT_H
#define ACCOUNT_H
class Account
{
private:
double balance; // Account balance
double interestRate; // Interest rate for the period
double interest; // Interest earned for the period
int transactions; // Number of transactions
public:
Account(double iRate = 0.045, double bal = 0)
{ balance = bal;
interestRate = iRate;
interest = 0;
transactions = 0; }
void setInterestRate(double iRate)
{ interestRate = iRate; }
void makeDeposit(double amount)
{ balance += amount; transactions++; }
bool withdraw(double amount); // Defined in Account.cpp
void calcInterest()
{ interest = balance * interestRate; balance += interest; }
double getInterestRate() const
{ return interestRate; }
double getBalance() const
{ return balance; }
double getInterest() const
{ return interest; }
int getTransactions() const
{ return transactions; }
};
#endif
int main()
{
Account Savings;
Account Checkings;
Account *ptr;
Account savings; // Savings account object
char choice; // Menu selection
// Set numeric output formatting.
cout << fixed << showpoint << setprecision(2);
do
{
// Display the menu and get a valid selection.
displayMenu();
cin >> choice;
while (toupper(choice) < 'A' || toupper(choice) > 'G')
{
cout << "Please make a choice in the range " << "of A through G:";
cin >> choice;
}
// Process the user's menu selection.
switch(choice)
{
case 'a':
case 'A': cout << "The current balance is $";
cout << savings.getBalance() << endl;
break;
case 'b':
case 'B': cout << "There have been ";
cout << savings.getTransactions() << " transactions.\n";
break;
case 'c':
case 'C': cout << "Interest earned for this period: $";
cout << savings.getInterest() << endl;
break;
case 'd':
case 'D': makeDeposit(savings);
break;
case 'e':
case 'E': withdraw(savings);
break;
case 'f':
case 'F': savings.calcInterest();
cout << "Interest added.\n";
}
} while (toupper(choice) != 'G');
return 0;
}
void displayMenu()
{
cout << "\n Welcome to The Bank \n";
cout << "-----------------------------------------\n";
cout << "A) Display the account balance\n";
cout << "B) Display the number of transactions\n";
cout << "C) Display interest earned for this period\n";
cout << "D) Make a deposit\n";
cout << "E) Make a withdrawal\n";
cout << "F) Add interest for this period\n";
cout << "G) Exit the program\n\n";
cout << "Enter your choice: ";
}
void makeDeposit(Account *acct)
{
double dollars;
cout << "Enter the amount of the deposit: ";
cin >> dollars;
cin.ignore();
acct.makeDeposit(dollars);
}
void withdraw(Account *acct)
{
double dollars;
cout << "Enter the amount of the withdrawal: ";
cin >> dollars;
cin.ignore();
if (!acct.withdraw(dollars))
cout << "ERROR: Withdrawal amount too large.\n\n";
}
Try something like this:
char displayAccountSelectionMenu();
char displayAccountActionMenu();
void makeDeposit(Account *acct);
void withdraw(Account *acct);
int main()
{
Account Savings;
Account Checkings;
Account *acct = NULL;
char choice; // Menu selection
do
{
// Display the menu and get a valid selection.
choice = displayAccountSelectionMenu();
// Process the user's menu selection.
switch (choice)
{
case 'A':
acct = &Savings;
break;
case 'B':
acct = &Checkings;
break;
case 'C':
return 0;
}
// Set numeric output formatting.
cout << fixed << showpoint << setprecision(2);
do
{
// Display the menu and get a valid selection.
choice = displayAccountActionMenu();
// Process the user's menu selection.
switch (choice)
{
case 'A':
cout << "The current balance is $"
<< acct->getBalance() << endl;
break;
case 'B':
cout << "There have been "
<< acct->getTransactions()
<< " transactions." << endl;
break;
case 'C':
cout << "Interest earned for this period: $"
<< acct->getInterest() << endl;
break;
case 'D':
makeDeposit(acct);
break;
case 'E':
withdraw(acct);
break;
case 'F':
acct->calcInterest();
cout << "Interest added." << endl;
break;
case 'G':
break;
case 'H':
return 0;
}
}
while (choice != 'G');
}
while (true);
return 0;
}
char displayAccountSelectionMenu()
{
char choice;
cout << "\n Welcome to The Bank \n";
cout << "-----------------------------------------\n";
cout << "Select an account:\n";
cout << "A) Savings\n";
cout << "B) Checking\n";
cout << "C) Exit the program\n\n";
cout << "Enter your choice: ";
cin >> choice;
choice = toupper(choice);
while ((choice < 'A') || (choice > 'C'))
{
cout << "Please make a choice in the range of A through C:";
cin >> choice;
choice = toupper(choice);
}
return choice;
}
char displayAccountActionMenu()
{
char choice;
cout << "\n Welcome to The Bank \n";
cout << "-----------------------------------------\n";
cout << "Select an action:\n";
cout << "A) Display the account balance\n";
cout << "B) Display the number of transactions\n";
cout << "C) Display interest earned for this period\n";
cout << "D) Make a deposit\n";
cout << "E) Make a withdrawal\n";
cout << "F) Add interest for this period\n";
cout << "G) Select a different account\n";
cout << "H) Exit the program\n\n";
cout << "Enter your choice: ";
cin >> choice;
choice = toupper(choice);
while ((choice < 'A') || (choice > 'H'))
{
cout << "Please make a choice in the range of A through H:";
cin >> choice;
choice = toupper(choice);
}
return choice;
}
void makeDeposit(Account *acct)
{
//...
}
void withdraw(Account *acct)
{
// ...
}

Menu driven project

The instructor want us to write a program that can re displays the menu only when the user wants to restart a selection and add an option to continue with another selection.
The problem I have is when the user select a number from 1 to 4 and complete the selection, the program will ask the user if the user want to continue with another selection and when the user says no, the program still ask to select a number without ending program.
here is my code that I've written so far:
#include<iostream>
using namespace std;
int sp;
int speed = 0;
int M, K, c, x;
const int MINspeed = 10;
const int MAXspeed = 40;
int GetSpeed();
int GetMinSpeed();
int GetMaxSpeed();
int CheckContinue();
int selection;
int GetSpeed()
{
char c;
while(true)
{
cout << "\nDo you want the speed in mph or km/h? \n"
<< "\nEnter M or K followed by Enter: " << endl;
cin >> c;
if( (c != 'M')&& (c != 'K'))
{
cout << "Incorrect Selection. Try Again! \n\n";
break;
}
if ( c == 'M')
{
cout << "\nSpeed in mph: " << speed << endl;
return speed;
}
else if(c == 'K')
{
double toKmPerHour = 1.61;
double speedInKmPerHour = speed * toKmPerHour;
cout << "\nSpeed in km/h:" << speedInKmPerHour << endl;
break;
}
CheckContinue();
}
return 0;
}
int GetMinSpeed()
{
cout << "MIN speed = " << MINspeed << endl;
CheckContinue();
return 0;
}
int GetMaxSpeed()
{
cout << "MAX speed = " << MAXspeed << endl;
CheckContinue();
return 0;
}
/*int SetSpeed(int sp)
{
cout << "The Set Speed is " << sp << endl;
return 0;
}
*/
void SetSpeed()
{
cout << "Input your speed: ";
cin >> speed;
CheckContinue();
}
int CheckContinue(void)
{
char x;
while(true)
{
cout << "\nDo you want to continue with another selection? \n"
<< "\nEnter Y or N followed by Enter: " << endl;
cin >> x;
if ( x == 'Y')
{
int selection;
cout << "Selection Menu" << endl;
cout << "--------------" << endl;
cout << "\n1. Set Speed" << endl;
cout << "2. Get Speed" << endl;
cout << "3. Get MAX Speed" << endl;
cout << "4. Get MIN Speed" << endl;
cout << "5. Exit" << endl;
cout << "\nYour selection :" <<endl;
cin >> selection;
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
break;
}
}
else if(x == 'N')
{
break;
}
}
return 0;
}
/*
In this menu function, it will ask the user to input the selection, ranging from 1 to 5.
If the user puts a number that is not between 1 to 5 or letters, then the program will
ask the user to input a valid selection.
*/
void menu()
{
int selection;
cout << "Selection Menu" << endl;
cout << "--------------" << endl;
cout << "\n1. Set Speed" << endl;
cout << "2. Get Speed" << endl;
cout << "3. Get MAX Speed" << endl;
cout << "4. Get MIN Speed" << endl;
cout << "5. Exit" << endl;
int bye = 0;
while(1)
{
cout << "\nYour selection :" <<endl;
cin >> selection;
bye = 0;
if((selection <= 5)&&(selection >= 1))
{
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
bye = -1;
break;
}
}
else
{
cout << "\nPlease input valid selection: " << endl;
cin >> selection;
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
bye = -1;
break;
}
}
if(bye == -1)
{
break;
}
}
}
int main()
{
menu();
return 0;
}//end of main function
This might serve your purpose. Call ask() as per your requirement if it didn't suit you.
#include <iostream>
#include <stdlib.h>
using namespace std;
char * title;
int a , b;
void menu();
void print(const char *c , int res )
{
cout<<"\n\n\n\n\nThe "<<c<<" of "<<a<<" and "<<b<<" is : " <<res<<endl;
}
void add()
{
print("Addition" , (a+b));
}
void sub()
{
print("subtraction" , (a-b));
}
void mul()
{
print("Multiplication" , (a*b));
}
void div()
{
print("Division" , (a/b));
}
void ask()
{
bool call_menu;
char ch;
cout<<"\n\n\n\n\n\n DO you Want to Continue? Y - N: ";
cin>>ch;
if(ch=='Y' || ch=='y')
{
call_menu= true;
}
else
{
if(ch=='N' || ch == 'n')
{
call_menu= false;
}
else
{
cin.clear();
ask();
}
}
if(call_menu)
{
system("clear"); // change this to system("cls") if on windows
menu();
}
else
{
system("clear"); // change this to system("cls") if on windows
cout<<"\n\n\n\n\n\n\n\t\t\tHave a Nice Day ! \n\n\n"<<endl;
}
}
void input(int *first , int *second)
{
system("clear"); // change this to system("cls") if on windows
cout<<"\n\n\n\t\t\t\t Calculator \n\n\n\n"<<endl;
cout<<"Enter the First Number : ";
cin>>(*first);
cout<<"\nEnter the Second Number :";
cin>>(*second);
}
void menu()
{
int ch;
cout<<"\n\n\n\t\t\t\t Calculator \n\n\n\n"<<endl;
cout<<"\n\n\t\t\t1 . Addition"<<endl;
cout<<"\n\n\t\t\t2 . Subtract"<<endl;
cout<<"\n\n\t\t\t3 . Multiply"<<endl;
cout<<"\n\n\t\t\t4 . Division"<<endl;
cout<<"\n\n\t\t\t5 . Exit" <<endl;
cout<<"\n\n\n\n Enter Your Choice : ";
cin>>ch;
if(ch >=1 && ch <5){
input(&a , &b);
}
switch(ch)
{
case 1:
add();
ask();
break;
case 2:
sub();
ask();
break;
case 3:
mul();
ask();
break;
case 4:
div();
ask();
break;
case 5:
exit(0);
break;
default:
system("clear"); // change this to system("cls") if on windows
cin.clear();
cin.ignore();
menu();
break;
}
}
int main(int argc, char **argv)
{
menu();
return 0;
}
Modify it as per your requirement.
There are several problems with the code in your question. The big problem is there is a lot of redundant code that can be easily eliminated by a few minor adjustments. You have both the menu printing and code to act on selections in several places. This is going to make managing the continue process a lot more difficult. By eliminating the redundant code and adjusting the logic in main and and menu you can not only reduce the complexity but make it far easier to manage.
For instance menu can be changed to remove the while loop and return a boolean value to indicate if the user wants to exit. This will allow you to select an option, act on it, then return letting other portions of the program handle asking the user if they want to continue.
The example below is a modification of your original code. It only addresses the logic for asking the user to continue and eliminates the redundant menu code. You should review the entire code and make additional adjustments as necessary.
#include <iostream>
#include <string>
using namespace std;
int sp;
int speed = 0;
int M, K, c, x;
const int MINspeed = 10;
const int MAXspeed = 40;
int GetSpeed()
{
char c;
while(true)
{
cout << "\nDo you want the speed in mph or km/h? \n"
<< "\nEnter M or K followed by Enter: " << flush;
cin >> c;
if( (c != 'M')&& (c != 'K'))
{
cout << "Incorrect Selection. Try Again! \n\n" << flush;
continue;
}
if ( c == 'M')
{
cout << "\nSpeed in mph: " << speed << endl;
return speed;
}
else if(c == 'K')
{
double toKmPerHour = 1.61;
double speedInKmPerHour = speed * toKmPerHour;
cout << "\nSpeed in km/h:" << speedInKmPerHour << endl;
return speed;
}
}
return 0;
}
int GetMinSpeed()
{
cout << "MIN speed = " << MINspeed << endl;
return 0;
}
int GetMaxSpeed()
{
cout << "MAX speed = " << MAXspeed << endl;
return 0;
}
void SetSpeed()
{
cout << "Input your speed: ";
cin >> speed;
}
/*
In this menu function, it will ask the user to input the selection, ranging from 1 to 5.
If the user puts a number that is not between 1 to 5 or letters, then the program will
ask the user to input a valid selection.
returns false if the user has selected the exit option
returns true for all other options
*/
bool menu()
{
cout << "Selection Menu" << endl;
cout << "--------------" << endl;
cout << "\n1. Set Speed" << endl;
cout << "2. Get Speed" << endl;
cout << "3. Get MAX Speed" << endl;
cout << "4. Get MIN Speed" << endl;
cout << "5. Exit" << endl;
int selection;
cout << "\nYour selection :" <<endl;
cin >> selection;
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
return false;
break;
default:
cout << "\nPlease input valid selection: " << endl;
}
return true;
}
int main()
{
for(bool process = true; process;)
{
process = menu();
if(process)
{
for(bool valid = false; !valid;)
{
cout << "\nDo you want to enter another selection? (Yes/No) " << flush;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string line;
getline(cin, line);
if(line == "No")
{
valid = true;
process = false;
}
else if(line == "Yes")
{
valid = true;
}
else
{
cout << "\nInvalid input\n\n" << flush;
}
}
}
}
return 0;
}//end of main function