Switch statement error in C++ - c++

Hello guys would someone please help me to fix this code of mine? It runs but it doesn't perform the task it should do. Once you run it, it automatically jumps in to the default statement and skips the cases. Please help me fix this thanks!
#include<iostream.h>
#include<conio.h>
using namespace std;
int main()
{
int choice;
char nbaPlayer, tele, food, subject, x;
cout << "This program determines your favorites.\n\n";
cout << "Please select the number of your corresponding choice.";
cout << "\n1. NBA Player";
cout << "\n2. Teleserye";
cout << "\n3. Food";
cout << "\n4. Subject";
cout << "\n5. Exit";
switch (choice)
{
case 1:
cout << "You have chosen NBA Player.\n";
cout << "Please enter your favorite NBA Player. \n";
cin >> nbaPlayer;
cout << "Your favorite NBA player is " << nbaPlayer;
break;
case 2:
cout << "You have chosen Teleserye.\n";
cout << "Please enter your favorite teleserye. \n";
cin >> tele;
cout << "Your favorite teleserye is " << tele;
break;
case 3:
cout << "You have chosen food.\n";
cout << "Please enter your favorite food. \n";
cin >> food;
cout << "Your favorite food is " << food;
break;
case 4:
cout << "You have chosen subject.\n";
cout << "Please enter your favorite subject. \n";
cin >> subject;
cout << "Your favorite subject is " << subject;
break;
case 5:
cout << "You chose to exit.\n";
break;
default:
cout <<"\nInvalid input";
}
getch();
}

You simply forgot:
cin>>choice
after you display available choice options. So when you never assign value to choice, it'll always choose default.

Related

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');.

How can I use an if statement within or outside of a switch statement (C++)

I am brand new to programming and am doing coding challenges found from here http://www.cplusplus.com/forum/articles/12974/. I cannot find the answer to my specific question through google searches, this is my first time posting here so I apologize if I've broken any guidelines! I am looking at the challenge which makes a user pick a number to select their favorite beverage.
I just learned about the switch statement and i named 5 cases, not including the default. I was trying to figure out how to incorporate an if statement inside of a switch statement (if this is even possible), or maybe it's a for loop that i am looking for? I am not sure but i'm willing to learn about whatever it is. I am trying to make it so that if the user does not enter a valid case number and it goes to default. (ex: anything other than 1, 2, 3, 4, or 5) I want the user to make another attempt at entering a correct number when it hits the default case.
This is my code
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
int choice;
cout << "Choose your beverage of choice by number: " << endl;
cout << "1. Coke" << endl;
cout << "2. Dr. Pepper" << endl;
cout << "3. Sprite" << endl;
cout << "4. Iced Tea" << endl;
cout << "5. Water" << endl;
cout << '\n';
cin >> choice;
cout << '\n' << "Choice entered: " << choice << endl;
cout << '\n';
switch (choice)
{
case 1 : cout << "You have chosen Coke." << endl;
break;
case 2 : cout << "You have chosen Dr. Pepper." << endl;
break;
case 3 : cout << "You have chosen Sprite." << endl;
break;
case 4 : cout << "You have chosen Iced Tea." << endl;
break;
case 5: cout << "You have chosen Water." << endl;
break;
default:
cout << "Error. Choice Not valid. Money returned." << endl;
break;
}
system("pause");
return 0;
}
I am trying to make it so that if the user does not enter a valid case number and it goes to default. (ex: anything other than 1, 2, 3, 4, or 5) I want the user to make another attempt at entering a correct number when it hits the default case.
One way to make this happen is to put a do-while loop around the block of code that receives user input and the switch statement.
int main()
{
bool isValidChoice = true;
do
{
// Reset when the loop is run more than once.
isValidChoice = true;
int choice;
cout << "Choose your beverage of choice by number: " << endl;
cout << "1. Coke" << endl;
cout << "2. Dr. Pepper" << endl;
cout << "3. Sprite" << endl;
cout << "4. Iced Tea" << endl;
cout << "5. Water" << endl;
cout << '\n';
cin >> choice;
cout << '\n' << "Choice entered: " << choice << endl;
cout << '\n';
switch (choice)
{
case 1 :
cout << "You have chosen Coke." << endl;
break;
case 2 :
cout << "You have chosen Dr. Pepper." << endl;
break;
case 3 :
cout << "You have chosen Sprite." << endl;
break;
case 4 :
cout << "You have chosen Iced Tea." << endl;
break;
case 5:
cout << "You have chosen Water." << endl;
break;
default:
cout << "Error. Choice Not valid. Money returned." << endl;
isValidChoice = false;
break;
}
} while ( !isValidChoice );
}

switch statement C++ [default part]

I'm writing a basic program about switch statement. The menu of 5 selections, if the use input invalid number, the user should be prompted again to make a selection (range is from 1-5). Here what I got so far:
#include <iostream>
#include "Menu.h"
using namespace std;
void Menu::inputChoices()
{
int choice;
cout << "IHCC Computer Science Registration Menu" << endl;
cout << "1. Welome to Computer Programming in C++" << endl;
cout << "2. Welcome to Java Programming" << endl;
cout << "3. Welcome to Android Programming" << endl;
cout << "4. Welcome to iOS Programming" << endl;
cout << "5. Exit" << endl;
cout << "\nEnter your selection: " << endl;
while ((choice = cin.get()) != EOF)
{
switch (choice)
{
case '1':
cout << "Welcome to Computer Programming in C++" << endl;
break;
case '2':
cout << "Welcome to Java Programming" << endl;
break;
case '3':
cout << "Welcome to Android Programming" << endl;
break;
case '4':
cout << "Welcome to iOS Programming" << endl;
break;
case '5':
cout << "Exiting program" << endl;
break;
default:
cout << "Invalid input. Re-Enter your selection: " << endl;
}
}
}
This project has 3 files, this is the source file. My problem is when I input a number is in the range (1-5), the default part of switch still also shows up. I just want show up my selection. Can anyone help me please! Thank you very much
The reason why you are also getting the default value is because cin.get() is reading the newline character (10).
I don't think using cin.get makes sense here since entering something like 23987928 or asdasf will output a ton of lines... You should use cin >> choice and convert your cases into ints. Something like:
cin >> choice;
switch (choice)
{
case 1:
cout << "Welcome to Computer Programming in C++" << endl;
break;
// ...
default:
cout << "Invalid input. Re-Enter your selection: " << endl;
}
The enter key '\n' should be handled. Try following and see if it works:
while ((choice = cin.get()) != EOF)
{
case 1:
// ...
// Basic idea is read extra `\n` and ignore it. Use below if condition
default:
if(choice != '\n')
cout << "Invalid input. Re-Enter your selection: " << endl;
}

Switch statemement reacting wrong after method getline c++

I am coding a banking app for university and i have stumbled upon a problem. Let's take for example a method of my class Customer.
void Customer::create_customer_data() {
cout << "Client' Address: ";
getline(cin, clientAddress);
cin.ignore();
cout << "Client's birth date: ";
getline(cin, clientBirthDate);
cin.ignore();
cout << "Client's telephone number: ";
getline(cin, clientTelephoneNumber);
cin.ignore();
cin.clear(); }
In the main function, i have a switch statement which handles the user choice.
int main() {
int choice, _globalClientNumber = 0;
Customer a(_globalClientNumber);
cout << "Welcome to bank manager 1.0!" << endl;
do {
cout << "Main Menu"<< endl;
cout << "Create a new customer (1)" << endl;
cout << "Create a new account (2)" << endl;
cout << "Cash money into account (3)" << endl;
cout << "Cash money out of account (4)" << endl;
cout << "Transfer money between two accounts (5)" << endl;
cout << "See current status of a customer and its accounts (6)" << endl;
cout << "End Application (0)" << endl;
cout << "Choice: ";
cin >> choice;
switch (choice) {
case 1:
a.create_customer_data();
break;
case 2:
a.create_new_account();
break;
case 3:
a.cash_in();
break;
case 4:
a.cash_out();
break;
case 5:
a.transfer_money();
break;
case 6:
a.print();
break;
default:
break;
}
cout << endl;
}
while (choice != 0);
return 0; }
The problem that i keep having is that the values that are written on the screen by the create_customer_data method are being processed by the do-while loop. So if the clientTelephoneNumber in the create_customer_data does not end in 0, the main menu is shown twice by the do-while loop. I would appreciate it if someone could tell me where my mistake is.
Edit: Shortly said: the choice variable gets overridden and the do-while loop gets executed once more resulting in double printing the menu.
i would say, that your cin needs to be flushed.
the answer can be found here:
How do I flush the cin buffer?

How do I prevent continuation of the program if player inputs invalid selection?

I created a text-based game to help improve my C++ skills since I am very new to it. I'm trying to learn the basics n' all.
Here is the program. In the switch statement, if a person were to select "3" it would broadcast an Error saying you can only select "1" or "2".
** The issue is the program continues and doesn't make the person RECHOOSE the selection. It goes right to Difficulty selecting.
What method do I use to force the program to halt until player chooses valid selection?
Thanks!
#include <iostream>
using namespace std;
int main()
{
cout << "\tWelcome to my text based game!\n";
char userName[100];
cout << "\nPlease enter your username: ";
cin >> userName;
cout << "Hello, " << userName << "!\n\n";
cout << "Please pick your race: \n";
cout << "1 - Human\n";
cout << "2 - Orc\n";
int pickRace;
cout << "Pick your race: ";
cin >> pickRace;
switch (pickRace)
{
case 1:
cout << "You picked the Human race." << endl;
break;
case 2:
cout << "You picked the Orc race." << endl;
break;
default:
cout << "Error - Invalid input; only 1 or 2 allowed!" << endl;
}
int difficulty;
cout << "\nPick your level difficulty: \n";
cout << "1 - Easy\n";
cout << "2 - Medium\n";
cout << "3 - Hard\n";
cout << "Pick your level difficulty: ";
cin >> difficulty;
switch (difficulty)
{
case 1:
cout << "You picked Easy" << endl;
break;
case 2:
cout << "You picked Medium" << endl;
break;
case 3:
cout << "You picked Hard" << endl;
break;
default:
cout << "Error - Invalid input, only 1,2 or 3 are allowed" << endl;
}
return 0;
}
You need to use loops. Wrap the input and the switch after it in a loop and break out of it when the input is valid.
Use a do ... while loop, like this
int pickRace;
do
{
cout << "Please pick your race: \n";
cout << "1 - Human\n";
cout << "2 - Orc\n";
cout << "Pick your race: ";
cin >> pickRace;
switch (pickRace)
{
case 1:
cout << "You picked the Human race." << endl;
break;
case 2:
cout << "You picked the Orc race." << endl;
break;
default:
cout << "Error - Invalid input; only 1 or 2 allowed!" << endl;
break;
}
}
while (pickRace != 1 && pickRace !=2);
This will keep on looping while the condition at the bottom is true (i.e. while they haven't picked a valid option).
One other comment. Since you are new you should really get into the habit of using string not char arrays. Char arrays will get you into all sorts of trouble in the future, so start using strings now. There's no point in learning bad habits.
#include <string>
string userName;
cout << "\nPlease enter your username: ";
cin >> userName;
cout << "Hello, " << userName << "!\n\n";
You can do - while loop with flags. The flag is by default false therefore allowing only one time input. If there is a need to enter another time, determined and controlled by the default case, then the flag is set to true, which makes the loop iterate once more. At the beginning of each iteration flag is reset to false, so each time it is assumed that this is the last one. Using flag will make the breaking operation much simple, and avoid complex while conditions.
int flag = 0;
do
{
cout << "Please pick your race: \n";
cout << "1 - Human\n";
cout << "2 - Orc\n";
cout << "Enter Choice: ";
cin >> pickRace;
flag = 0;
switch (pickRace)
{
case 1:
cout << "You picked the Human race." << endl;
break;
case 2:
cout << "You picked the Orc race." << endl;
break;
default:
cout << "Error - Invalid input; only 1 or 2 allowed!" << endl;
flag = 1;
}
} while (flag);