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.
Related
Here's a small snippet of my code. The purpose of the snippet you see here is twofold 1)present a menu -- that's the menu() function, and 2) prompt the user to make a selection and store it -- selection().
selection() starts on line 18.
I'm trying to declare some variables that will be local to my menu() and selection() functions, but I get errors like this, for everything I try to declare:
warning: unused variable 's' (it gave this for all my 'char' variables)
or
error: 'snack_selection' was not declared in this scope (it gave this for the two 'int' variables I tried to declare)
but how can that be? I don't know what I'm missing.
patient feedback is appreciated.
int menu(void)
{
cout << "Available snacks to select from: " << endl //presents menu
<< " " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25"
<< endl //prompts user to make a selection (until it is valid)
<< " " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35"
<< endl
<< " " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95"
<< endl
<< " " << setw(5) << "C - Cookies" << setw(14) << "$1.50"
<< endl
<< " " << setw(5) << "B - Brownie" << setw(14) << "$1.75"
<< endl
<< " " << setw(5) << "N - Nuts" << setw(17) << "$1.40"
<< endl;
selection();
return 0;
}
int selection(void) //FUNCTION: welcomes, presents menu, and prompts user for selection
{
int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
char snack_selection = 0; //condition for snack_selection switch case statement
char P, S, T, C, B, N; //the char variables needed for the snack_selection
cout << "Please enter the letter labeling your snack selection: ";
cin >> snack_selection;
cout << endl;
switch(std::toupper(snack_selection))
{ //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
break;
case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
break;
case 'T': price = pop_tart_price;
break;
case 'C': price = cookies_price;
break;
case 'B': price = brownie_price;
break;
case 'N': price = nuts_price;
break;
default:
cout << "Invalid selection!";
menu();
} //end of switch statement
return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}
full code here with superficial info removed:
#include <iostream>
#include <iomanip>
#include <cctype>
using namespace std;
//Variable Declarations
int price = 0, total_paid = 0, total_price = 0; //arguments for the three functions in the program.need to be global
//Function Declarations:
int menu(void);
// presents menu
int selection(void);
//prompts user to make selection and stores it
int accept_money(int price);
//tells user what money it accepts and the label for each type
//1. repeats back what cost is
//2. tells what has been paid
//3. allows user to input money by payment selection here
int compute_change(int total_paid, int total_price);
//1. tells user what total amt was paid
//2. computes change
//3. tells user what change will be
//4. ask user if he or she would like another purchase (if statement. if y, send back to int menu(). if no, thank for purchase message.)
int main()
{
cout << "Welcome to the snack vending machine" << endl << endl;
menu();
accept_money(price);
compute_change(total_paid, total_price);
return 0;
}
//Function Definitions
int menu(void)
{
cout << "Available snacks to select from: " << endl //presents menu
<< " " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25"
<< endl //prompts user to make a selection (until it is valid)
<< " " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35"
<< endl
<< " " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95" <<
endl
<< " " << setw(5) << "C - Cookies" << setw(14) << "$1.50" <<
endl
<< " " << setw(5) << "B - Brownie" << setw(14) << "$1.75" <<
endl
<< " " << setw(5) << "N - Nuts" << setw(17) << "$1.40" <<
endl;
selection();
return 0;
}
int selection(void) //FUNCTION: welcomes, presents menu, and prompts user for selection
{
int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
char snack_selection = 0; //condition for snack_selection switch case statement
char P, S, T, C, B, N; //the char variables needed for the snack_selection switch case statement (can't be inside function, needs to be global
cout << "Please enter the letter labeling your snack selection: ";
cin >> snack_selection;
cout << endl;
switch ( std::toupper(snack_selection) )
{ //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
break;
case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
break;
case 'T': price = pop_tart_price;
break;
case 'C': price = cookies_price;
break;
case 'B': price = brownie_price;
break;
case 'N': price = nuts_price;
break;
default:
cout << "Invalid selection!";
menu();
} //end of switch statement
return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}
int accept_money(int price)
{
int nickel = 5, quarter = 25, dollar = 100;
char money_selection = 0; //condition for money_selection switch case statement
char n, q, d; //the char variables needed for the money_selection switch case statement
cout << "Money accepted by the machine:\n"
<< " " << setw(5) << "N - Nickel" << endl
<< " " << setw(5) << "Q - Quarter" << endl
<< " " << setw(5) << "D - Dollar" << endl << endl;
do
{
cout << "Your selected snack item cost: " << price << " CENTS" << endl
<< "Your total inserted: " << total_paid << " CENTS" << endl
<< "Insert amount (enter letter of choice): ";
cin >> money_selection;
cout << endl;
switch ( std::tolower(money_selection) )
{
case 'n': total_paid = nickel + total_paid;
cout << endl;
break;
case 'q': total_paid = quarter + total_paid;
cout << endl;
break;
case 'd': total_paid = dollar + total_paid;
cout << endl;
break;
default:
cout << money_selection << " is not recognized as a coin." << endl << endl;
}
} while ( total_paid < price );
return total_paid; //this function needs to return updated value, or any changes made to it will remain local to the function
}
int compute_change(int total_paid, int total_price)
{
char continue_purchase = 0;
char y;
int change = total_paid - price; //has to have somewhere to be stored in this function to work
int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable
cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
<< "Dispensing change: " << change << setw(5) << " CENTS" << endl
<< "Would you care to make another purchase (Y/N): ";
cin >> continue_purchase;
switch ( std::tolower(continue_purchase) )
{
case 'y': total_paid = 0;
price = 0;
total_price = 0;
cout << endl << endl;
menu();
break;
case 'n': cout << "Thank you and enjoy your purchase!";
break;
default:
cout << "Invalid Selection" << endl << endl;
compute_change(total_paid, total_price);
}
return 0;
}
Apart from what everyone said in the comments about not using global variables and other good programming practices, the code itself compiles fine (unless you have -Werror switch in your compiler flags active like me.) BUT with warnings.
You seem to have misunderstood that if you are going to use the string literal 'P' in a case statement, as you are doing in the function int selection(void) , that you have to first declare a variable char P for that. You do NOT have to declare a variable for using those string literals. There is NO connection whatsoever between the variable char P and the string 'P'.
The warnings, come from these lines:
In the function int compute_change(int total_paid, int total_price) remove the following line:
char y;
Then in the function int accept_money(int price) remove the following line:
char n, q, d; //the char variables needed for the money_selection switch case statement
And finally in the function int selection(void) //FUNCTION: welcomes, presents menu, and prompts user for selection
remove the following line.
char P, S, T, C, B, N; //the char variables needed for the snack_selection switch case statement (can't be inside function, needs to be global
You would be fine after that.
If you really really want to use those variables, P, S and so on, then you should assign them a value and declare them to be constant. I did one of the cases here, for you to see. You can do the rest along similar lines.
int compute_change(int total_paid, int total_price)
{
char continue_purchase = 0;
const char y = 'y';
int change = total_paid - price; //has to have somewhere to be stored in this function to work
int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable
cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
<< "Dispensing change: " << change << setw(5) << " CENTS" <<
endl
<< "Would you care to make another purchase (Y/N): ";
cin >> continue_purchase;
switch(std::tolower(continue_purchase))
{
case y:
total_paid = 0;
price = 0;
total_price = 0;
cout << endl << endl;
menu();
break;
case 'n': cout << "Thank you and enjoy your purchase!";
break;
default:
cout << "Invalid Selection" << endl << endl;
compute_change(total_paid, total_price);
}
return 0;
}
But just to make it clear, that variable y could've been named anything- it does not have to be named y to store 'y'. The code would've worked just fine if I replace that line with const char hakunamatata = 'y'
int compute_change(int total_paid, int total_price)
{
char continue_purchase = 0;
const char hakunamatata = 'y';
int change = total_paid - price; //has to have somewhere to be stored in this function to work
int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable
cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
<< "Dispensing change: " << change << setw(5) << " CENTS" <<
endl
<< "Would you care to make another purchase (Y/N): ";
cin >> continue_purchase;
switch(std::tolower(continue_purchase))
{
case hakunamatata:
total_paid = 0;
price = 0;
total_price = 0;
cout << endl << endl;
menu();
break;
case 'n': cout << "Thank you and enjoy your purchase!";
break;
default:
cout << "Invalid Selection" << endl << endl;
compute_change(total_paid, total_price);
}
return 0;
}
The compiler warns you about unused variables/parameters as it reveals genuine errors of oversight/omission,etc on your part (e.g. in this case as you seem to have misunderstood that declaring a char variable is needed to use a string literal containing the same text as the name of that char variable). See this question for more on that: What are the consequences of ignoring: warning: unused parameter
Hope that helps.
The code compiles fine but contains warnings of unused variables. In 3 places you declare char variables which are unused. Removing these declarations gets rid of the warnings. Here I've posted the modified code.
#include <iostream>
#include <iomanip>
#include <cctype>
using namespace std;
//Variable Declarations
int price = 0, total_paid = 0, total_price = 0; //arguments for the three functions in the program.need to be global
//Function Declarations:
int menu(void);
// presents menu
int selection(void);
//prompts user to make selection and stores it
int accept_money(int price);
//tells user what money it accepts and the label for each type
//1. repeats back what cost is
//2. tells what has been paid
//3. allows user to input money by payment selection here
int compute_change(int total_paid, int total_price);
//1. tells user what total amt was paid
//2. computes change
//3. tells user what change will be
//4. ask user if he or she would like another purchase (if statement. if y, send back to int menu(). if no, thank for purchase message.)
int main()
{
cout << "Welcome to the snack vending machine" << endl << endl;
menu();
accept_money(price);
compute_change(total_paid, total_price);
return 0;
}
//Function Definitions
int menu(void)
{
cout << "Available snacks to select from: " << endl //presents menu
<< " " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25"
<< endl //prompts user to make a selection (until it is valid)
<< " " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35"
<< endl
<< " " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95" <<
endl
<< " " << setw(5) << "C - Cookies" << setw(14) << "$1.50" <<
endl
<< " " << setw(5) << "B - Brownie" << setw(14) << "$1.75" <<
endl
<< " " << setw(5) << "N - Nuts" << setw(17) << "$1.40" <<
endl;
selection();
return 0;
}
int selection(void) //FUNCTION: welcomes, presents menu, and prompts user for selection
{
int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
char snack_selection = 0; //condition for snack_selection switch case statement
cout << "Please enter the letter labeling your snack selection: ";
cin >> snack_selection;
cout << endl;
switch ( std::toupper(snack_selection) )
{ //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
break;
case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
break;
case 'T': price = pop_tart_price;
break;
case 'C': price = cookies_price;
break;
case 'B': price = brownie_price;
break;
case 'N': price = nuts_price;
break;
default:
cout << "Invalid selection!";
menu();
} //end of switch statement
return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}
int accept_money(int price)
{
int nickel = 5, quarter = 25, dollar = 100;
char money_selection = 0; //condition for money_selection switch case statement
cout << "Money accepted by the machine:\n"
<< " " << setw(5) << "N - Nickel" << endl
<< " " << setw(5) << "Q - Quarter" << endl
<< " " << setw(5) << "D - Dollar" << endl << endl;
do
{
cout << "Your selected snack item cost: " << price << " CENTS" << endl
<< "Your total inserted: " << total_paid << " CENTS" << endl
<< "Insert amount (enter letter of choice): ";
cin >> money_selection;
cout << endl;
switch ( std::tolower(money_selection) )
{
case 'n': total_paid = nickel + total_paid;
cout << endl;
break;
case 'q': total_paid = quarter + total_paid;
cout << endl;
break;
case 'd': total_paid = dollar + total_paid;
cout << endl;
break;
default:
cout << money_selection << " is not recognized as a coin." << endl << endl;
}
} while ( total_paid < price );
return total_paid; //this function needs to return updated value, or any changes made to it will remain local to the function
}
int compute_change(int total_paid, int total_price)
{
char continue_purchase = 0;
int change = total_paid - price; //has to have somewhere to be stored in this function to work
int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable
cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
<< "Dispensing change: " << change << setw(5) << " CENTS" << endl
<< "Would you care to make another purchase (Y/N): ";
cin >> continue_purchase;
switch ( std::tolower(continue_purchase) )
{
case 'y': total_paid = 0;
price = 0;
total_price = 0;
cout << endl << endl;
menu();
break;
case 'n': cout << "Thank you and enjoy your purchase!";
break;
default:
cout << "Invalid Selection" << endl << endl;
compute_change(total_paid, total_price);
}
return 0;
}
I need cherries, oranges, plumes, bells, melons, or bars to be randomly picked in the case statements and in a way I can then display what was chosen so I can compare them, but I'm not sure how.
For example, I was hoping when I printed slot1, slot2, and slot3, I would get the names of which case statement inside each of the three switches were chosen.
Not their numbers. (The program isn't done yet so it's quite messy right now)
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int main()
{
int slot1;
int slot2;
int slot3;
double won;
double money;
string cherries;
string oranges;
string plums;
string bells;
string melons;
string bars;
string doAgain;
do
{
cout << "We are going to be playing a slot machine game today." << endl;
cout << "Please enter the amount of money you'd like to insert into the slot machine." << endl;
cin >> money;
cout << "You put in $" << money << endl;
srand(time(0));
slot1=rand()%6+1;
slot2=rand()%6+1;
slot3=rand()%6+1;
switch (slot1)
{
case 1:
cout << cherries << endl;
case 2:
cout << oranges << endl;
break;
case 3:
cout << plums << endl;
break;
case 4:
cout << bells << endl;
break;
case 5:
cout << melons << endl;
break;
case 6:
cout << bars << endl;
}
switch (slot2)
{
case 1:
cout << melons << endl;
break;
case 2:
cout << bells << endl;
break;
case 3:
cout << bars << endl;
break;
case 4:
cout << plums << endl;
break;
case 5:
cout << oranges << endl;
break;
case 6:
cout << cherries << endl;
}
switch (slot3)
{
case 1:
cout << bars << endl;
break;
case 2:
cout << plums << endl;
break;
case 3:
cout << melons << endl;
break;
case 4:
cout << bells << endl;
break;
case 5:
cout << oranges << endl;
break;
case 6:
cout << cherries << endl;
}
cout << "The numbers you got were " << slot1 << ", " << slot2 << ", " << slot3 << endl;
cout << "Would you like to play again?" << endl;
cin >> doAgain;
if(doAgain!= "yes")
{
cout << "The total amount of money you put in the slot machine is" << money << endl;
cout << "The total amount of money you won is $" << won << endl;
}
}
while(doAgain=="yes");
return 0;
}
enter code here
You have declared strings for all the various fruits, but you don't assign any actual string values to them. ie string cherries = "cherries"
Just printing slot1 will only print an int as you have discovered. C++ doesn't know that you also want to print the name as well. You need to include your string as part of the cout statement
I got 158, 1000, and 140 for the money outputs while I played.
The original amount I put in was 100.
The total amount of money and the amount of money entered by the user aren't showing up correctly when ran.
Sometimes, the total and the amount entered displays correctly, it should be noted.
But not always, and that's a problem.
There is some logic error(s) I can't figure out. Help?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <stdlib.h>
using namespace std;
void switchStatementsCalculations (int &slot1, int &slot2, int &slot3, string cherries, string
oranges, string plums, string bells, string melons, string bars);
void calculateAmountEarnedByPlaying (double &money, int slot1, int slot2, int slot3,
double &total);
int main()
{
int slot1;
int slot2;
int slot3;
double money=0;
double total=0;
double amountOfMoneyEnterd=0;
int count;
string cherries = "cherries";
string oranges = "oranges";
string plums = "plums";
string bells = "bells";
string melons = "melons";
string bars = "bars";
string doAgain;
cout << "We are going to be playing a slot machine game today." << endl;
srand(time(0));
do
{
cout << "Please enter the amount of money you'd like to insert into the slot machine. We will pull the lever for you." << endl;
cin >> money;
cout << "You put in $" << money << endl;
slot1=rand()%6+1;
slot2=rand()%6+1;
slot3=rand()%6+1;
switchStatementsCalculations(slot1, slot2, slot3, cherries, oranges, plums, bells, melons, bars);
calculateAmountEarnedByPlaying(money, slot1, slot2, slot3, total);
amountOfMoneyEnterd=(amountOfMoneyEnterd+money);
cout << "Would you like to play again? Please type yes if so." << endl;
cin >> doAgain;
if(doAgain!= "yes")
{
cout << "The total amount of money you put in the slot machine is " << amountOfMoneyEnterd << endl;
cout << "The total amount of money you won is $" << total << endl;
}
}
while(doAgain=="yes");
system("Pause");
return 0;
}
void switchStatementsCalculations(int &slot1, int &slot2, int &slot3, string cherries, string
oranges, string plums, string bells, string melons, string bars)
{
switch (slot1)
{
case 1:
cout << "You got " << cherries << endl;
case 2:
cout << "You got " << oranges << endl;
break;
case 3:
cout << "You got " << plums << endl;
break;
case 4:
cout << "You got " << bells << endl;
break;
case 5:
cout << "You got " << melons << endl;
break;
case 6:
cout << "You got " << bars << endl;
}
switch (slot2)
{
case 1:
cout << "You got " << cherries << endl;
break;
case 2:
cout << "You got " << oranges << endl;
break;
case 3:
cout << "You got " << plums << endl;
break;
case 4:
cout << "You got " << bells << endl;
break;
case 5:
cout << "You got " << melons << endl;
break;
case 6:
cout << "You got " << bars << endl;
}
switch (slot3)
{
case 1:
cout << "You got " << cherries << endl;
break;
case 2:
cout << "You got " << oranges << endl;
break;
case 3:
cout << "You got " << plums << endl;
break;
case 4:
cout << "You got " << bells << endl;
break;
case 5:
cout << "You got " << melons << endl;
break;
case 6:
cout << "You got " << bars << endl;
}
}
void calculateAmountEarnedByPlaying(double &money, int slot1, int slot2, int slot3, double &total)
{
double won=0;
if(slot1==slot2 || slot1==slot3 || slot2==slot3)
{
cout << "Congratulations! You won." << endl;
won=(money * 2);
cout << "You won " << won << endl;
}
else if ((slot1==slot2 && slot1==slot3) || (slot2==slot1 && slot2==slot3) || (slot3==slot1 && slot3==slot2))
{
cout << "Congratulations! You won." << endl;
won=(money*3);
cout << "You won " << won << endl;
}
else
{
cout << "You didn't earn any money." << endl;
}
total=(total+won);
}
One mistake is this in your calculateAmountEarnedByPlaying function:
double won;
You did not initialize this variable, thus it contains an indeterminate value.
It is only set if you've won something, but not set if you didn't win. You then do this at the end of your function:
total = (total + won);
If won is not initialized, then total will also be set to an indeterminate value (or undefined behavior occurs).
The won variable should be initialized to 0:
double won = 0;
Most compilers give a warning if you access an uninitialized variable like this. Please check that you have your warnings on to detect these issues.
The other issue is that you forgot a break in your switch statements:
switch (slot1)
{
case 1:
cout << "You got " << cherries << endl; // no break statement
case 2:
cout << "You got " << oranges << endl;
break;
If slot1 is 1, it will print both sets of output for case 1 and case 2.
None of this would be necessary if you used arrays instead of 6 separate variables and 6 separate lines of output:
std::string slot_items[] = {"cherries", "oranges", "plums", "bells", "melons", "bars"};
//...
int slots[3];
//...
for (int i = 0; i < 3; ++i)
slots[i] = rand()%6+1;
//...
// inside the function...
//...
for (int i = 0; i < 3; ++i)
cout << "You got " << slot_items[slots[i]] << endl;
A two line for loop replaces 60 lines of switch and case statements.
Hello I'm beginning to learn c++ , I don't understand how enum works that well and I need help knowing how can I make the rand() working with enum
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
cout << "First part : Create an item. " << endl;
int choice;
int Fire = 25;
int Water = 23;
int Wind = 24;
int Earth = 20;
int WeaponNature = 0;
enum NatureWeapons { Fire, Water, Wind, Earth}; // enum here if its wrong pls let me know ):
cout << "Enter the nature of weapon you want : " << endl;
cout << " 1 - Fire " << endl;
cout << " 2 - Water " << endl;
cout << " 3 - Wind " << endl;
cout << " 4 - Earth" << endl;
cin >> choice;
switch(choice)
{
case 1:
cout << "You picked fire."
cout << " Power : " << Fire << endl;
WeaponNature = Fire;
break;
case 2:
cout << "You picked water." << endl;
cout << " Power : " << Water << endl;
WeaponNature = Water;
break;
case 3:
cout << "You picked wind nature." << endl;
cout << " Power : " << Wind << endl;
WeaponNature = Wind;
break;
case 4:
cout << "You picked earth nature." << endl;
cout << " Power : " << Earth << endl;
WeaponNature = Earth;
break;
default:
cout << "Incorrect input. Your weapon will be : " << rand() // this is where i need help
}
}
When the default: runs in the switch() i wanted it to choose a random nature with rand(), please any help ): ?
As take from http://www.cprogramming.com/tutorial/enum.html:
Printing Enums
You might wonder what happens when you print out an enum: by default, you'll get the integer value of the enum. If you want to do something fancier than that, you'll have to handle it specially.
You would have to create another switch block converting the random integer into the proper value from the enum. Also, initialise a seed for your random number generator via srand( time( NULL ) )
Assign the rand value to WeaponNature as well.
I want to have a function called "userPrompt" andit ask for the user to enter a value for integer named "choose" so after that I would be able to use switch statement.
But It dosen't work it says: "choose" undeclared.
I suppose it would start the main function first,and inside of it the first command would be initializing the userPrompt func. then thanks to userPrompt I would have a choose value so that the switch would work.
So what is the problem with this code?
How can I use nested functions?(I hope it is called like that)
Is my code's order wrong?
Any help will be appreciated.
userPrompt(){
int choose;
cout << " Please Choose An Option : " << endl;
cout << " Type 1 to Add new grades : " << endl;
cout << " Type 2 to Calculate the average grades : " << endl;
cout << " Type 3 to Calculate the total grades : " << endl;
cout << " Type 4 to Exit : " << endl;
cin >> choose;
}
int main()
{
userPrompt();
switch(choose){
case 1
getGrade();
userPrompt();
break;
case 2
int average;
getGrade();
average = total/counter;
cout << average;
break;
case 3
getGrade();
cout << total;
break;
case 4
cout << "Thanks for Trying" << endl;
return 0;
system("pause");
break;
default
cout << "Please Choose A Valid Option ! : " << endl;
validOption();
}
}
C++ uses "scope" which sort of translates into the "visibility" of variables. The "choose" variable of your userPrompt() function is only "visible" (within reach) inside the scope of the userPrompt() function.
So you could declare the userPrompt() function as
int userPrompt() // Returns the user choice
{
... // your existing code here
return choose;
}
Then inside main() you would do something like:
int main()
{
int choice = userPrompt();
switch(choice)
...
You forgot to put colon in your case and also you need to return choose.
case 1:
Try this:
int userPrompt(){
int choose;
cout << " Please Choose An Option : " << endl;
cout << " Type 1 to Add new grades : " << endl;
cout << " Type 2 to Calculate the average grades : " << endl;
cout << " Type 3 to Calculate the total grades : " << endl;
cout << " Type 4 to Exit : " << endl;
cin >> choose;
return choose;
}
int main()
{
int choose = userPrompt();
switch(choose){
case 1:
getGrade();
userPrompt();
break;
case 2:
int average;
getGrade();
average = total/counter;
cout << average;
break;
case 3:
getGrade();
cout << total;
break;
case 4:
cout << "Thanks for Trying" << endl;
return 0;
system("pause");
break;
default:
cout << "Please Choose A Valid Option ! : " << endl;
validOption();
}
}
change the code to this :
int userPrompt(){ //--> changed into a function returning the choice
int choose;
cout << " Please Choose An Option : " << endl;
cout << " Type 1 to Add new grades : " << endl;
cout << " Type 2 to Calculate the average grades : " << endl;
cout << " Type 3 to Calculate the total grades : " << endl;
cout << " Type 4 to Exit : " << endl;
cin >> choose;
return choose;
}
int main()
{
//--> declare choose in main and assign a value using the function call
int choose = userPrompt();
switch(choose){
case 1:
getGrade();
userPrompt();
break;
case 2:
int average;
getGrade();
average = total/counter;
cout << average;
break;
case 3:
getGrade();
cout << total;
break;
case 4:
cout << "Thanks for Trying" << endl;
return 0;
system("pause");
break;
default
cout << "Please Choose A Valid Option ! : " << endl;
validOption();
}
}
Simple mistake. put colon in cases case 1: like that
`intialize the choose first and try it.
int choose = o;
In C++ every function has a return type. This means that it will return something or return void (i.e, return nothing). In your program userPrompt has no return type neither void or any other return type hence this part is the first error in your program.
The next error is that after every case label in the switch statement that label must be followed by a colon ':'