C++ Program menu using do while and switch - c++

I am able to display the program menu to the user, but I can't get the actual math to execute. For example, when I enter 2 it only displays 0, instead of letting me enter two integers and then either multiplying them or adding them. How can I get it to allow the user to enter options for 1, 2, or 3, and then have it do what they entered?
#include <iostream>
using namespace std;
int main()
{
int choice;
int numberOne = 0;
int numberTwo = 0;
int sumOfTwoNumbers = 0;
int productOfTwoNumbers = 0;
do{
cout <<"Please select one of the following options: \n";
cout << "1: Enter two integer values\n"
"2: Add the two values\n"
"3: Multiply the two values\n"
"4: Exit\n";
cout << "Enter your selection (1, 2,3 or 4): ";
std::cin >> choice;
switch (choice)
{
case 1:
cout << "Enter two integer values. " << endl;
cin >> numberOne >> numberTwo;
break;
case 2:
sumOfTwoNumbers = numberOne + numberTwo;
cout << sumOfTwoNumbers << endl;
break;
case 3:
productOfTwoNumbers = numberOne * numberTwo;
cout << productOfTwoNumbers << endl;
break;
case 4:
cout << "You have chosen Exit, Goodbye.";
break;
default:
cout<< "Your selection must be between 1 and 4!\n";
break;
}
}while(choice!= '4');
return 0;
}

You only ask for the two numbers in case 1. In the other options the numbers are left as their default value of 0. You need to make sure that you assign the two numbers no matter which option is chosen. Also your cases don't make much sense as all of the options require inputting two numbers. I remove case 1 and simply move the lines
cout << "Enter two integer values. " << endl;
cin >> numberOne >> numberTwo;
Above the switch statement:
cout <<"Please select one of the following options: \n";
cout <<
"1: Add the two values\n"
"2: Multiply the two values\n"
"3: Exit\n";
cout << "Enter your selection (1, 2, or 3): ";
std::cin >> choice;
cout << "Enter two integer values. " << endl;
cin >> numberOne >> numberTwo;
switch (choice)
{
case 1:
sumOfTwoNumbers = numberOne + numberTwo;
cout << sumOfTwoNumbers << endl;
break;
case 2:
//etc

Related

C++ Error: Continue option is not working and is looping the program instead

Note: I am a beginner in C++, so please bear with me if there are any serious programming errors that can be fixed easily.
Edit: Options 3 and 4 work perfectly fine without any errors. However, Option 2 has a serious looping problem where 'Error! Number should be in range of (1 to 100)' and 'Enter the number again:' loop continuously when you input any key. Will change the code to show the code for Option 2 and remove Option 3 and Option 4's code.
I created a math program that can calculate numbers, calculate fractions, among other features I added. I added a continue button on some programs (Option 2) that when you enter 'Y' on your keyboard, it should loop the program until the user types a different key to signify that the program should stop. However, the continue button seems not to work. When I press any other key, the program still loops and I have to stop the program so it cannot loop.
#include <<iostream>>
#include <<cmath>>
using namespace std;
int main()
{
std::cout << "Math Application Version 0.1 (currently in development)\n";
std::cout << "Choose an application to use (use numbers 1 - 10)\n":
std::cout << "Option 1: Calculator" << std::endl "Option 2: Use Average Calculator" <<
std::endl << "Option 3: Use Fraction Calculator\n" << std::endl <<
"Option 4: Use LCM (Lowest Common Denominator) Calculator\n";
int choice;
std::cin >> choice;
switch (choice)
{
case 1:
// this is blank on purpose because this would get too long if I added more features here
case 2:
{
printf("\n Chose average calculator.");
char d;
int n, i;
float num[100],
sum=0.0,
average;
anon:
{
cout << "Enter the numbers of data (limit is 100) : ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! Number should be in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for (i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
}
cout << "\nDo you want to continue? "; cin >> n;
if (n== 'Y', "Yes")
goto anon;
system("PAUSE");
return 0;
break;
}
I'd appreciate any help on this issue or a detailed explanation since this is very confusing for me.
Your code is fine but you just have some typos in these lines.
cout << "\nDo you want to continue? ";
cin >> n;
/*Here => */ if (n== 'Y', "Yes")
fix it to if(n == 'Y'), also you have unintentionally used n instead of the char d that you have defined to use as a check.
So your code should be
cout << "\nDo you want to continue? ";
cin >> d;
if (d == 'Y') { .... }
And for completion, avoid goto whenever you can. You can use a while loop instead of the assembly-like goto.
This is your code but with a while loop instead of goto
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
std::cout << "Math Application Version 0.1 (currently in development)\n";
std::cout << "Choose an application to use (use numbers 1 - 10)\n";
std::cout << "Option 1: Calculator" << std::endl << "Option 2: Use Average Calculator" <<
std::endl << "Option 3: Use Fraction Calculator\n" << std::endl <<
"Option 4: Use LCM (Lowest Common Denominator) Calculator\n";
int choice;
std::cin >> choice;
switch (choice)
{
case 1:
// this is blank on purpose because this would get too long if I added more features here
case 2:
printf("\n Chose average calculator.");
char d = 'Y';
int n, i;
float num[100],
sum=0.0,
average;
while (d == 'Y'){
cout << "Enter the numbers of data (limit is 100) : ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! Number should be in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for (i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
cout << "\nDo you want to continue? ";
cin >> d;
}
break;
}
}

Undeclared identifier- C++

I am doing a project for school and keep running into this reoccurring problem, my code does not seem to run as I have "undeclared identifiers." I have tried renaming them or redefining them but the same errors keep going or more. I am using VS code at the moment and read about maybe it was VScode itself but I get the same errors regardless.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
using namespace std;
class bankAccount {
public:
int accountNum;
string accountName;
string accountType;
double accountBalance;
double accountInterest;
double getInterest;
double updateBalance;
bankAccount(){
accountNum = 0;
accountName = "";
accountType = "";
accountBalance = 0.0;
accountInterest = 0.0;
}
void deposit()
{
long amount;
cout << "\n Please enter the amount you would like to deposit: ";
cin >> amount;
accountBalance = accountBalance + amount;
}
void withdraw()
{
long amount;
cout << "Please enter the amount you would like to withdraw: ";
cin >> amount;
if (amount <= accountBalance)
{
accountBalance = accountBalance - amount;
}
else
{
cout << "You do not have sufficient funds" << endl;
}
}
void interest(){
double getInterest;
cout << "Please enter desired interest amount: ";
cin >> getInterest;
}
void update(){
double updateBalance;
updateBalance = accountBalance * getInterest;
accountBalance += updateBalance;
}
void print(){
string print;
cout << "Welcome Back " << accountName << "," << endl;
cout << "\n Account Number: " << accountNum << endl;
cout << "\n Account Type: " << accountType << endl;
cout << "\n Current Balance: " << accountBalance << endl;
cout << "\n Account Interest: " << accountInterest << endl;
}
void openAccount(){
cout << "Enter Account Number: ";
cin >> accountNum;
cout << "Enter Account Holders Name: ";
cin >> accountName;
cout << "Enter Account Type: ";
cin >> accountType;
cout << "Enter Initial Balance: ";
cin >> accountBalance;
cout << "Enter Interest Rate: ";
cin >> accountInterest;
}
};
int main() {
int choice;
do
{
cout << "Please select the following options ";
cout << "\n 1:View Account";
cout << "\n 2: Open Account";
cout << "\n 3: Deposit" ;
cout << "\n 4: Withdraw ";
cout << "\n 5: Update account";
cin >> choice;
switch (choice)
{
case '1':
print ();
break;
case '2':
openAccount();
break;
case '3':
deposit();
break;
case '4':
withdraw();
break;
case '5':
updateBalance();
break;
}
} while (case !=5);
}
suggested creating an instance of class bankAccount somewhere before switch statement and call the functions like, instance_of_bankAccount.functionName();
At end of loop instead of (case !=5) it should be (choice != 5)
The problem with your code is that you do not have any instance of the class bankAccount, which means you try to call the function which actually does not exist. To fix it, you should create an object of the bankAccount type before the loop in which you can select the operation you want to perform:
int main() {
int choice;
bankAccount bankAcc; // this creates the object we need
do ...
And then for every case you wanted to call the function f(), add prefix bankAcc., so it becomes bankAcc.f(). In your code, it would be:
switch (choice) {
case '1':
bankAcc.print();
break;
case '2':
bankAcc.openAccount();
break;
case '3':
bankAcc.deposit();
break;
case '4':
bankAcc.withdraw();
break;
case '5':
bankAcc.updateBalance();
break;
}
Thanks to it, all functions called will know that they belong to bankAcc and they will change properties only of this particular object.
There is also another mistake in your code: did you really mean to use chars in your switch? At the moment cin >> choice reads an int, saves it in choice and then in switch it gets compared with all values corresponding to cases. The problem is that 1 is very different from '1' (which is casted to the value 49), so inputted int will never satisfy conditions from the menu you print.
Also, while (case !=5) should be changed to while (choice != 5).

do-while loop with switch statements-- infinity loop error

I am just trying to create a simple "menu". Basically user can input their selection and when they enter 'E', it should exit the menu. I can't catch why its giving me an infinity loop-- i know its most likely my while loop(?). its all just hard-coded as im just trying to get the gist of it.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
char choice;
int numOfCups;
cout << "Hot Beverage Menu: \n";
cout << "A: Coffee $1.00 \n";
cout << "B: Tea $0.75 \n";
cout << "C: Hot Chocolate: $1.25 \n";
cout << "D: Cappuccino: $2.50 \n";
cout << "E: Exit Menu \n";
cout << "Please make a drink selection:";
cin >> choice;
do {
switch(choice) {
case 'A': cout << "You chose Coffee \n";
cout << "How many cups would you like?";
cin >> numOfCups;
cout << "Your total will be: " << '$' << fixed << setprecision(2) << (1.00 * numOfCups) << endl;
cout << "Please make another selection:";
cin >> choice;
break;
case 'B': cout << "You chose Tea \n";
cout << "How many cups would you like? \n";
cin >> numOfCups;
cout << "Your total will be: \n" << '$' << fixed << setprecision(2) << (0.75 * numOfCups) << endl;
cout << "Please make another selection:";
cin >> choice;
break;
case 'C': cout << "You chose Hot Chocolate \n";
cout << "How many cups would you like? \n";
cin >> numOfCups;
cout << "Your total will be: \n" << '$' << fixed << setprecision(2) << (1.25 * numOfCups) << endl;
cout << "Please make another selection:";
cin >> choice;
break;
case 'D': cout << "You chose Cappuccino \n";
cout << "How many cups would you like? \n";
cin >> numOfCups;
cout << "Your total will be: \n" << '$' << fixed << setprecision(2) << (2.50 * numOfCups) << endl;
cout << "Please make another selection:";
cin >> choice;
break;
case 'E': cout << "Exit Menu";
break;
default: cout << "Invalid input. Please make another selection.";
break;
}
} while (choice == 'E');
return 0;
}
Loop continues as long as the condition is true, and finishes when the condition is false. Instead of while (choice == 'E') you should have while (choice != 'E').
Also, you should add cin >> choice; to the default condition, or you will have an infinite loop in that case.
Try do ... while (choice != 'E');.

Switch menu calculator will not display arithmetic

Sorry if the title is confusing, I did not know how to word my issue very well.
I understand some of my program is not finished as of right now, I'm currently only working on the keyboard input sections.
Basically, I have to create a program that allows the user to either input a file with set integers or have the user enter two integers of their own. This user is also asked which arithmetic they would like performed on their integers. I created a menu and sub menus using a switch statement that would allow the user to easily navigate to their destination.
My problem is, when I try to use the input through keyboard option, my program fails to display the calculated variable. I can fully navigate to the option and even input my integers but when the program displays the final answer it states: "The total is: menu" and then it kicks me back to the main menu.
My specific example:
User selects (2) for keyboard input.
User selects (1) for addition arithmetic
User enters an integer (1)
User enters another integer (2)
Program displays "The total is: Menu"
Program loops back to main menu.
Here is my code:
#include "complx.h"
#include <iostream> using namespace std;
ifstream infile ("in.dat");
int main() {
int choiceOne, choiceOneSubMenu, choiceTwoSubMenu, digitOne, digitTwo, digitTotal;
bool menu = true;
do{
cout << "Menu \n";
cout << "=========== \n";
cout << "(1) Input from a file \n";
cout << "(2) Input from the keyboard \n";
cout << "(3) Exit the program \n";
cout << "Enter a numerical selection: \n";
cin >> choiceOne;
switch (choiceOne) {
case 1:
cout << "You chose input from a file \n";
cout << "=============== \n";
cout << "Which arithmetic would you like applied? \n";
cout << "(1) Addition + \n";
cout << "(2) Subtraction - \n";
cout << "(3) Multiplication * \n";
cout << "(4) Division / \n";
cout << "Enter a numerical selection: \n";
cin >> choiceOneSubMenu;
switch (choiceOneSubMenu) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
}
break;
case 2:
cout << "You chose input from the keyboard \n";
cout << "=============== \n";
cout << "Which arithmetic would you like applied? \n";
cout << "(1) Addition + \n";
cout << "(2) Subtraction - \n";
cout << "(3) Multiplication * \n";
cout << "(4) Division / \n";
cout << "Enter a numerical selection: \n";
cin >> choiceTwoSubMenu;
switch (choiceTwoSubMenu)
{
case 1:
cout << "You chose addition \n";
cout << "=============== \n";
cout << "Enter your first integer: \n";
cin >> digitOne;
cout << "Enter your second integer: \n";
cin >> digitTwo;
digitTotal = (digitOne + digitTwo);
cout << "The total is: " + digitTotal;
break;
case 2:
cout << "You chose subtraction \n";
cout << "=============== \n";
cout << "Enter your first integer: \n";
cin >> digitOne;
cout << "Enter your second integer: \n";
cin >> digitTwo;
digitTotal = (digitOne - digitTwo);
cout << "The total is: " + digitTotal;
break;
case 3:
cout << "You chose multiplication \n";
cout << "=============== \n";
cout << "Enter your first integer: \n";
cin >> digitOne;
cout << "Enter your second integer: \n";
cin >> digitTwo;
digitTotal = (digitOne * digitTwo);
cout << "The total is: " + digitTotal;
break;
case 4:
cout << "You chose division \n";
cout << "=============== \n";
cout << "Enter your first integer: \n";
cin >> digitOne;
cout << "Enter your second integer: \n";
cin >> digitTwo;
digitTotal = (digitOne / digitTwo);
cout << "The total is: " + digitTotal;
break;
}
break;
case 3:
cout << "You have chosen to exit";
}
}while(choiceOne!=3);
}
cout << "The total is: " + digitTotal;
you can't simply convert digit to string and concatenate it using + operator.
Edit:
you can do it like this:
cout << "The total is: " << itoa(digitTotal);
or these

Alternatives of switch [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In the below code, I need help with the alternatives of switch case, I mean how can I avoid switch and use the other option to execute the code.
Code:
cout << " *********************Intensive Program 1***********************\n\n" << endl;
cout << "\nHere's the menu of choices: ";
cout << "\n1. Add a Circle.\n";
cout << "2. Print a Circle. \n";
cout << "3. Print all Cricles \n";
cout << "4. Exit.\n";
cout << "\nPlease enter your choice: ";
cin >> choice;
while (choice <4){
switch (choice){
case 1:
// For adding cirles to the class
cout << " Enter the value for the radius of the circle: ";
cin >> radius;
cout << " Enter the value for the center of the circle: ";
cin >> center;
myCircle[thisPosition] = new Circle(radius, center);
myCircle[thisPosition]->PrintCircle();
thisPosition++;
break;
case 2: // For printing a particular cirle from the list of cirles
cout << " Enter the Value for which Circle to Print: ";
cin >> printPosition;
myCircle[printPosition - 1]->PrintCircle();
break;
case 3: // For printing all the circles in the class object array pointer list
cout << "\n";
for (int i = 0; i < thisPosition; i++){
myCircle[i]->PrintCircle();
cout << "\n==============================" << endl;
}
break;
case 4:
cout << "\n Good Bye !!! \n " << endl;
break;
}
cout << "\nHere's the menu of choices: ";
cout << "\n1. Add a Circle.\n";
cout << "2. Print a Circle. \n";
cout << "3. Print all Cricles \n";
cout << "4. Exit.";
cout << "Please enter your choice: ";
cin >> choice;
system("pause");
}
}
You could also use a std::vector<std::function<void()>> choices(5);... and call it like choices[choice](); after you filled it with the alternative choices like choices[1] = &function_1; etc...
But I have a feeling the real question is not really about how to avoid switch...
[EDIT]
Based on your comment, I think the question is how to avoid duplicating the "menu" output. Simply refactor like this using a do..while:
cout << " *********************Intensive Program 1***********************\n\n" << endl;
cout << "\nHere's the menu of choices: ";
cout << "\n1. Add a Circle.\n";
cout << "2. Print a Circle. \n";
cout << "3. Print all Cricles \n";
cout << "4. Exit.\n";
cout << "\nPlease enter your choice: ";
do
{
cin >> choice;
switch (choice){
case 1:
// For adding cirles to the class
cout << " Enter the value for the radius of the circle: ";
cin >> radius;
cout << " Enter the value for the center of the circle: ";
cin >> center;
myCircle[thisPosition] = new Circle(radius, center);
myCircle[thisPosition]->PrintCircle();
thisPosition++;
break;
case 2: // For printing a particular cirle from the list of cirles
cout << " Enter the Value for which Circle to Print: ";
cin >> printPosition;
myCircle[printPosition - 1]->PrintCircle();
break;
case 3: // For printing all the circles in the class object array pointer list
cout << "\n";
for (int i = 0; i < thisPosition; i++){
myCircle[i]->PrintCircle();
cout << "\n==============================" << endl;
}
break;
case 4:
cout << "\n Good Bye !!! \n " << endl;
break;
}
system("pause");
}
} while(choice != 4);
If you still want the menu to be repeated for each choice, then simply cut and paste the menu printing at the start of the do..while loop.
As a side note, I strongly suggest you read https://mikeash.com/getting_answers.html for the next time.
Using if-else ladder is one of the alternatives for switch statements.
cout << " *********************Intensive Program 1***********************\n\n" << endl;
cout << "\nHere's the menu of choices: ";
cout << "\n1. Add a Circle.\n";
cout << "2. Print a Circle. \n";
cout << "3. Print all Cricles \n";
cout << "4. Exit.\n";
cout << "\nPlease enter your choice: ";
cin >> choice;
while (choice <4){
if(choice==1)
{
// For adding cirles to the class
cout << " Enter the value for the radius of the circle: ";
cin >> radius;
cout << " Enter the value for the center of the circle: ";
cin >> center;
myCircle[thisPosition] = new Circle(radius, center);
myCircle[thisPosition]->PrintCircle();
thisPosition++;
}
else if(choice==2)
{ // For printing a particular cirle from the list of cirles
cout << " Enter the Value for which Circle to Print: ";
cin >> printPosition;
myCircle[printPosition - 1]->PrintCircle();
}
else if(choice==3) // For printing all the circles in the class object array pointer list
{
cout << "\n";
for (int i = 0; i < thisPosition; i++){
myCircle[i]->PrintCircle();
cout << "\n==============================" << endl;
}
}
else
{
cout << "\n Good Bye !!! \n " << endl;
}
}
system("pause");
}