C++ input error with switch statment and function [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 months ago.
Improve this question
I don't know why but my code is not working when I sign out a book and click a number and then try to sign in a book it says I have the number one choice(Python book) even if i click any other option. I don't know why.It's probably something dumb so please go easy on me.
#include <iostream>
using namespace std;
string book;
void menu(){
cout << "*********Menu*********";
cout << "\n1) Sign out book";
cout << "\n2) sign in book";
cout << "\n3) See my books";
cout << "\n4) Exit";
}
void book1(){
book = {"Computer Science"};
}
void book2(){
book = {"Programming with C++"};
}
void book3(){
book = {"Python Programming"};
}
int main(){
//Vars
int choice;
do
{
menu();
cin >> choice;
switch (choice)
{
case 1:
int book_choice;
cout << "\n**********************";
cout << "\n1) Computer Science";
cout << "\n2) Programming with C++";
cout << "\n3) Python Programming";
cin >> book_choice;
switch (book_choice)
{
case 1:
book1();
case 2:
book2();
case 3:
book3();
default:
break;
}
break;
case 2:
cout << "\n**********************";
cout << "\nSigned out books: ";
cout << book;
//add books
case 3:
cout << "\n**********************";
default:
break;
}
} while (choice != 4);
}

The error lies in the book_choice switch:
switch (book_choice)
{
case 1:
book1();
// missing break;
case 2:
book2();
// missing break;
case 3:
book3();
// missing break;
default:
break;
}
You forgot to use break; after each case. The default behaviour in a switch is to fall through and execute the next case. That means you always end up executing book3() and setting your book to "Python Programming".

Related

Why am I getting an infinite loop when using do-while loop with my print function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to make a menu of different functions which supposed to run until the user inputs the 'Q' or 'q' character. When I try to run the program, it keeps on looping the default switch case. Am I using the wrong loop?
#include <iostream>
#include <vector>
using namespace std;
bool getout{false};
char cases ;
void menu(){
cout << "\n\nP - Print Number\nA - Add Number\nM - Display mean of the number\nS - Display the smallest number\nL - -Display the largest number\nQ - Quit\n\nEnter your choice: " << endl;
}
char read(){
cin>> cases;
}
int main(){
do{
void menu();
void read();
switch (cases){
case 'p':
case 'P': void print();
break;
case 'S':
case 's':
void smallest();
break;
case'Q':
case 'q':
getout=true;
break;
default:
cout<<"Please input a valid option";
}//switch braces
}
while (getout==false);
return 0;}
Your read() function doesn't return anything in spite of being marked as returning a char. You call the function incorrectly in your main function as well. This is the main culprit.
Remove the word void.
I've attached a touched-up version of your code. It moves the global variables into the main function (globals are a thing to avoid whenever possible), and fixes the read function to return a character. I can never tell if the poor formatting in the question is a copy-paste issue, or your code is legitimately that sloppy, but in either case I also formatted it.
#include <iostream>
#include <vector>
void menu() {
std::cout
<< "\n\nP - Print Number\nA - Add Number\nM - Display mean of the "
"number\nS - Display the smallest number\nL - -Display the largest "
"number\nQ - Quit\n\nEnter your choice: ";
}
char read() {
char choice;
std::cin >> choice;
return choice;
}
int main() {
bool getout{false};
do {
menu();
char cases = read();
switch (cases) {
case 'p':
case 'P':
void print();
break;
case 'S':
case 's':
void smallest();
break;
case 'Q':
case 'q':
getout = true;
break;
default:
std::cout << "Please input a valid option";
} // switch braces
} while (getout == false);
return 0;
}

C++ need help, random switch statements [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm writing a code which is kind of like a fortune teller but I'm having some trouble with my switch statements. When executed the code prints out the same message and doesn't pick a random case like its supposed to! can someone please help me! thank you!
heres my code
#include<iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
void printGreeting(); // function prototype
int main()
{
int choice;
printGreeting();
cout << "Would you like to see your fortune?" << endl;
cout << "Press 1 to see your fortune or 2 if you don't!" << endl;
cin >> choice;
if (choice == 1)
{
cout << "Great! Your fortune is: ";
// Function to generate random number
void rand1();
srand(time(NULL));
int MAX_NUM;
MAX_NUM = 5;
int random = rand() % MAX_NUM;
cout << random << endl;
int selection;
selection = 5;
switch (selection)
{
case 1:
cout << "Change can hurt, but it leads a path to something better!";
break;
case 2:
cout << "If you have something good in your life don't let it go!";
break;
case 3:
cout << "You're in for a treat today.";
break;
case 4:
cout << "Land is always on the mind of a flying bird";
break;
case 5:
cout << "A dream you have will come true";
break;
}
return 0;
}
else if (choice == 2)
{
cout << "Okay goodbye!" << endl;
}
}
// Prints greeting message
void printGreeting() // function header
{
cout << "Hello! Welcome to your fortune teller!" << endl; // function body
}
Because selection = 5;
You want to choose selection with a random value between 1 - 5, right?
You switch by selection variable, which is explicitly set to 5 right before the switch itself. Consider switching by random variable.

C++ switch not working with more than 2 cases [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm learning C++ so sorry for newbie question.
I'm doing exercises from S. Prata's Book. I'm currently on 6.4.
There is the code I've written:
#include <iostream>
using namespace std;
void showmenu();
void request();
const int strsize = 20;
const int templeSize = 5;
struct temple {
char name[strsize];
char job[strsize];
char psd[strsize];
int preference;
};
int main(){
temple members[templeSize] = {
{"Alan", "spy", "Kret", 0},
{"Bruce", "engi", "Mech", 2},
{"Zac", "engi", "Robot", 0},
{"Kevin", "teacher", "Kid", 1},
{"Maverick", "spy", "Shadow", 2}
};
char choice;
showmenu();
request();
cin >> choice;
while (choice != 'q'){
switch(choice){
case 'a' : for(int i; i< templeSize; i++)
cout << members[i].name << endl;
break;
case 'b' : for(int i; i< templeSize; i++)
cout << members[i].job << endl;
break;
case 'c' : for(int i; i< templeSize; i++)
cout << members[i].psd << endl;
break;
case 'd' : for(int i; i < templeSize;i++){
switch(members[i].preference){
case 0: cout << members[i].name; break;
case 1: cout << members[i].job; break;
case 2: cout << members[i].psd; break;
}
}
default : request();
}
showmenu();
cin >> choice;
}
cout << "\nBye!\n";
return 0;
}
void request(){
cout << "Choose one option:\n";
}
void showmenu(){
cout << "a. names b. jobs\n"
"c. psds d. preferences\n"
"q. Quit\n";
}
I have no ide what is wrong with that. Code is compiling (I'm using code::blocks), but only for cases 'a' and 'b'. When I input 'c' or 'd' it just showing menu again. Same if I choose a/b more than once.
I've found other solution via google, but I realy want to know what is wrong with my code.
i is not initialized in any of your case statement for loops
You are calling showmenu() outside of your switch statement. So no matter what the input you will leave the switch and call the function.
switch(choice){
...
}
showmenu();
...

C++ function that returns value into switch statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Currently I have a working program, but am trying different things to see if they work. below is the code I am trying to get to work but having a function that asks the user to make a selection. I want to return that value into my main function which will run a do while loop that includes a case. Originally I have it as an if else if statement, but want to cut that down if possible. Below is the code I am working with. When running the program it only returns the entire menu instead of running the function from the value that should be returned.
{
int choice;
createEmptySeats();
seatPrice();
do {
choice = menu();
switch (choice)
{
case '1':
reserveSeat();
break;
case '2':
displayInfo();
break;
case '3':
DisplaySummary();
break;
case '4':
break;
}
}
while (!seatFull());
return 0;
}
int menu()
{
int userSelection = -1;
while (userSelection < 1 || userSelection > 4)
{
cout << "Please Choose Option Below" << endl;
cout << "1: Reserve Seat(s)"<<endl;
cout << "2: Display Available Seats" << endl;
cout << "3: Display Information:" << endl;
cout << "4: Exit System" << endl;
cin >> userSelection;
}
return userSelection;
}
First: You're missing break; in your switch statement for each of the cases, except case 4 (not sure if it's by design).
Second: Choice is int, your cases are chars. Change one of them, so that both of them match. You're never finding a match for your case, so you just keep on looping.
choice is int, and you write char - '1', '2' in the case. Write as follows:
choice = menu();
switch (choice)
{
case 1:
reserveSeat();
break;
case 2:
displayInfo();
break;
// ...
In your code you can come to case '1' when choice is an ASCII code of '1', i.e. 49. In your code it could never happen, so you stuck in the infinite loop with menu().

C++ Text based game [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am currently making a small console based text game in C++ with visual studio 2010.
I have encounted the problem of; when I get my name entered and difficulty selected I go to make the introductory text and I enter :
cout <<"Welcome "<<userName<<"... You are a lone: "<<pickRace<<" Your journey will be a "<<difficulty<<" one.";
And I want it to show up as : Welcome Blake... you are a lone Human/Orc your journey will be a easy/medium/hard one.
But I comes up as Welcome Blake... you are a lone 1/2 your jouney will be a 1/2/3 one.
this is a problem I think due to my switch's could anyone tell me how I need to rewrite them to get it appear with the name instead of numbers?
original code :
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.\n";
break;
case 2:
cout <<"You Picked the Orc race\n";
break;
default:
cout <<"Error - Invalid imput; only 1 or 2 allowed.\n";
}
int difficulty;
cout <<"\nPick your level diffuculty: \n";
cout <<"1 - Easy\n";
cout <<"1 - Medium\n";
cout <<"3 - Hard\n";
cout <<"Pick your level difficulty: ";
cin >>difficulty;
switch (difficulty)
{
case 1:
cout <<"You picked Easy.\n\n";
break;
case 2:
cout <<"You picked Medium.\n\n";
break;
case 3:
cout <<"You picked Hard.\n\n";
break;
default:
cout <<"Error - Invalid imut; only 1,2 or 3 allowed.\n";
}
You are storing pickRace and difficulty as integers. Try doing something like:
int pickRace;
string raceText; //we will store the race type using this
cout <<"Pick your race: ";
cin >>pickRace;
switch (pickRace)
{
case 1:
cout <<"You picked the Human race.\n";
raceText = "Human";
break;
case 2:
cout <<"You Picked the Orc race\n";
raceText = "Orc";
break;
default:
cout <<"Error - Invalid imput; only 1 or 2 allowed.\n";
}
Note the raceText string variable.
Repeat this for difficulty.
Then use raceText and difficultyText to print your message:
out <<"Welcome "<<userName<<"... You are a lone: "<<raceText<<" Your journey will be a "<<difficultyText<<" one.";
Consider using enums and overload operator<< and operator>> for them:
#include <iostream>
#include <cassert>
enum difficulty { EASY = 1, MEDIUM = 2, HARD = 3 };
std::istream& operator>>( std::istream& is, difficulty& d )
{
int i;
is >> i;
assert( i > 0 && i < 4 ); // TODO: Use real error handling, throw an exception
d = difficulty( i );
return is;
}
std::ostream& operator<<( std::ostream& os, difficulty d )
{
switch( d ) {
case EASY: return os << "easy";
case MEDIUM: return os << "medium";
case HARD: return os << "hard";
}
return os << "unknown[" << (int)d << "]";
}
int main()
{
difficulty d;
std::cout << "Pick difficulty: 1-easy, 2-medium, 3-hard: ";
std::cin >> d;
std::cout << "You picked difficulty: " << d << std::endl;
}
Why do you expect it to print string when you are storing choices as ints...
You can use std::map
#include <map>
std::map<int, std::string> difficulty;
difficulty[1] = "easy";
difficulty[2] = "medium";
difficulty[3] = "hard";
int choice_difficulty;
std::cin>>choice_difficulty;
/*Check if user entered correct number*/
std::map<int, std::string>::iterator it = difficulty.find(choice_difficulty);
if(it == difficulty.end())
std::cout << "wrong choice";
cout <<"Welcome "<<userName<<" Your journey will be a "<<difficulty[choice_difficulty];
You may want to use lookup tables to convert between enums or numeric IDentifiers (IDs) and the text they represent.
For example:
struct Race_Text_Entry
{
const char * text;
unsigned int id;
};
static const Race_Text_Entry race_name_table[] =
{
{"Unknown", 0},
{"Human", ID_HUMAN_RACE},
{"Orc", ID_ORC_RACE},
{"Elf", ID_ELF_RACE},
};
static const unsigned int NUM_RACE_ENTRIES =
sizeof(race_name_table) / sizeof(race_name_table[0]);
std::string Race_ID_To_Text(unsigned int id)
{
unsigned int i = 0;
std::string race_name = "Race unknown";
for (i = 0; i < NUM_RACE_ENTRIES; ++i)
{
if (race_name_table[i].id == id)
{
race_name = race_name_table.text;
break;
}
}
return race_name;
}
int main(void)
{
std::cout << "My race: " << Race_ID_To_Text(ID_RACE_HUMAN) << "\n";
return 0;
}
A nice advantage to the constant lookup table as an array, is that it can be stored in the read-only data section of the program and loaded with the constant data. The initialization time is negligible compared with creating a std::map variable during initialization.
pickRace and difficulty are Integers. You're printing integers instead of the actual difficulty. You need to somehow logically represent the difficulty (and pickRace)