while loop multiple statements - c++

I have some issues with looping. I am trying to loop multiple statements. Code is below.
int MenuSelect () {
cout << endl;
cout << YELLOW << "Enter 1 for info" << endl;
cout << " " << endl;
cout << "Enter 2 to Start" << endl;
cout << " " << endl;
cout << "Enter 3 to view settings" << endl;
cout << " " << endl;
cout << "Enter 4 to quit" << endl;
int selected = 0;
string input;
cin >> input;
if (stringstream(input) >> selected) {
return selected;
}
else {
return -1;
}
return 0;
};
int Menu(int) {
int selected {};
while ((selected = MenuSelect()) == 1) {
printmessage();
}
if (selected == 3) {
cout << "Current Settings" << endl;
somefunction();
}
else if (selected == 2) {
cout << "Starting Game..... " << endl;
}
else if (selected == 4) {
cout << "Exiting....." << endl;
exit (3);
}
else {
cout << "Invalid Entry" << endl;
exit (3);
}
cout << "Below is the Deck of cards and you will get to choose 5 cards to play with. Choose wisely." << endl;
return 0;
};
So as you can see the user can see the menu, then if and else statements do the work. At the moment I have managed to loop the first menu select so if the user enters 1 it will print the message and then loop back to the menu. What I want is to also loop the 3 - current settings and if the user enters a invalid number. I've tried to accomplish it but I can't seem to do it.

You probably want to repeatedly read user input and react accordingly? You can put all the ifs into the while:
int Menu(int) {
int selected {};
bool loop = true;
while (loop) {
selected = MenuSelect();
if(selected == 1) {
printmessage();
}
else if (selected == 3) {
cout << "Current Settings" << endl;
somefunction();
}
else if (selected == 2) {
cout << "Starting Game..... " << endl;
}
else if (selected == 4) {
cout << "Exiting....." << endl;
loop = false;
}
else {
cout << "Invalid Entry" << endl;
loop = false;
}
}
cout << "Below is the Deck of cards and you will get to choose 5 cards to play with. Choose wisely." << endl;
return 0;
};
Using a variable loop to exit the while is just personal preference, you could as well have an endless loop
while(true)
and use break; to exit the loop or exit() to exit the whole program, as you do now.

Related

I've been working on my introduction to C++ project which is to make a game of NIM

I've been working on my introduction to C++ project which is to make a game of NIM. I've written program and I thought it should run smoothly but I've countered the following errors.
I know too much code but I couldn't figure out what is the issue that is stopping me from running the program.
I'm new to the programming word so be understanding if the issue is very simple.
thank you in advance.
Error Message
#include <iostream>
#include <iomanip>
using namespace std;
int stonesNum;
char goFirst;
int turn = 0; // 0 = player, 1 = computer
int stonesRemove;
int main() {
do
{
cout << "Enter number of starting stones:" << endl;
cin >> stonesNum;
cout << "Would you like to go first? (y/n)" << endl;
cin >> goFirst;
if (goFirst == 'y' || goFirst == 'Y')
{
turn = 0;
}
else
{
turn = 1;
}
while (stonesNum > 0)
{
if (turn == 0)
{
cout << "How many would you like to remove: 1 or 2?" << endl;
cin >> stonesRemove;
stonesNum = stonesNum - 1;
cout << "The number of stones left is " << stonesNum << endl;
}
else
{
if (stonesNum % 3 == 0)
{
stonesNum = stonesNum - 2;
cout << "The computer removes 2 stones." << endl;
cout << "The number of stones left is " << stonesNum << endl;
}
else
{
stonesNum = stonesNum - 1;
cout << "The computer removes 1 stones." << endl;
cout << "The number of stones left is " << stonesNum << endl;
}
}
if (stonesNum == 0)
{
if (turn == 0)
{
cout << "The computer wins!" << endl;
}
else
{
cout << "you won!" << endl;
}
}
}
}
return 0;
}
You are missing an ending while condition after your do loop. The syntax is :
do{
//do stuff here
}while(condition);
In your case the condition would be (stonesNum!=0)
OR
Do
if (stonesNum == 0)
{
if (turn == 0)
{
cout << "The computer wins!" << endl;
return;
}
else
{
cout << "you won!" << endl;
return;
}
}
and put condition (true)
You actually don't require the do loop at all, are you trying to loop the game endlessly? If so then you should put an appropriate prompt at the beginning and put condition (true) in the do loop.
The complete code:
do
{
cout << "Enter number of starting stones:" << endl;
cin >> stonesNum;
cout << "Would you like to go first? (y/n)" << endl;
cin >> goFirst;
if (goFirst == 'y' || goFirst == 'Y')
{
turn = 0;
}
else
{
turn = 1;
}
while (stonesNum > 0)
{
if (turn == 0)
{
cout << "How many would you like to remove: 1 or 2?" << endl;
cin >> stonesRemove;
stonesNum = stonesNum - 1;
cout << "The number of stones left is " << stonesNum << endl;
}
else
{
if (stonesNum % 3 == 0)
{
stonesNum = stonesNum - 2;
cout << "The computer removes 2 stones." << endl;
cout << "The number of stones left is " << stonesNum << endl;
}
else
{
stonesNum = stonesNum - 1;
cout << "The computer removes 1 stones." << endl;
cout << "The number of stones left is " << stonesNum << endl;
}
}
}
if (turn == 0)
{
cout << "The computer wins!" << endl;
}
else
{
cout << "you won!" << endl;
}
}while(true);

Getting loop to redisplay message c++

I am trying to get a program to display a menu with options, then given the user input, display a certain message. After it displays their message I want the loop to go back to displaying the message until they choose the quit option. How do I get the loop to return to displaying the menu after any choice of 1-3?
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int menu_choice;
cout << "Select a numerical option:" << endl << "=== menu ===" << endl << "1. Fox" << endl << "2. Bunny" << endl << "3. Sloth" << endl << "4. Quit" << endl;
cin >> menu_choice;
while (menu_choice >= 1 && menu_choice <= 4)
{
while (menu_choice == 1)
{
cout << "1 work" << endl;
menu_choice = 0;
continue;
}
while (menu_choice == 2)
{
cout << "2 work" << endl;
menu_choice = 0;
continue;
}
while (menu_choice == 3)
{
cout << "3 work" << endl;
menu_choice = 0;
continue;
}
while (menu_choice == 4)
{
cout << "4 work" << endl;
menu_choice = 0;
continue;
}
}
return 0;
}
Your code is displaying the menu only 1 time. If the user enters an invalid choice, you exit right away. If the user enters a valid choice, you do the chosen work, but then you exit rather than display the menu again. All of your while..continue loops are completely useless, they only run 1 time at most, setting the menu_choice to 0, which breaks your outer while loop so it runs only 1 time as well.
You need an outer loop that runs continuously, displaying the menu each time, until you are actually ready to exit.
You should also replace the useless while..continue loops with if/else blocks, or better a single switch block.
Try something more like this instead:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int menu_choice;
do
{
cout << "Select a numerical option:" << endl
<< "=== menu ===" << endl
<< "1. Fox" << endl
<< "2. Bunny" << endl
<< "3. Sloth" << endl
<< "4. Quit" << endl;
if (!(cin >> menu_choice))
{
menu_choice = 0;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
switch (menu_choice)
{
case 1:
cout << "1 work" << endl;
break;
case 2:
cout << "2 work" << endl;
break;
case 3:
cout << "3 work" << endl;
break;
case 4:
cout << "4 work" << endl;
break;
default:
cout << "Bad choice! Try again" << endl;
break;
}
}
while (menu_choice != 4);
return 0;
}
#Remy Lebeau was quicker posting and his answer is well written, but since I was done writing the code and you might benefit looking at different implementations I'm posting the code. I deliberately chose not to use switch since you might not have seen it before.
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
bool quit = false;
int menu_choice;
while(!quit) {
cout << "Select a numerical option:" << endl
<< "=== menu ===" << endl
<< "1. Fox" << endl
<< "2. Bunny" << endl
<< "3. Sloth" << endl
<< "4. Quit" << endl;
if(cin >> menu_choice) {
if(menu_choice == 1) {
cout << "1 work" << endl;
}
if(menu_choice == 2) {
cout << "2 work" << endl;
}
if(menu_choice == 3) {
cout << "3 work" << endl;
}
if(menu_choice == 4) {
cout << "Bye" << endl;
quit = true; // Set quit to true to stop the while loop
} else {
cout << "Invalid number" << endl;
}
} else {
cout << "Bad input" << endl;
cin.clear();
cin.ignore();
}
}
return 0;
}
Note that the cin.ignore and cin.clear are important and often confuse people new to this. Read this question for the details.

Why won't my Do-while loop work to run the Menu in C++

I know I am probably missing something obvious, but my code will only run the do loop in the main function once. After the selected function (with menu selection) is ran the program exits instead of restarting the loop. I am not sure what is wrong with my loop. Please Advise.
P.S. This program is written in C++
Here is the entire body of the program. All of the functions work with the exception of the do loop in the main function.
//It also includes functions to cancel a selection and to show all seats on the flight.
//These allow the predefined functions within the program to operate.
#include <iostream>
#include <string>
//This sets the namespace of the entire program to std
using namespace std;
//This creates a constant variable for the rows of seats on the flight.
const int rows = 13;
//This creates a constant variable for the seats in each row on the flight.
const int seats = 6;
//This line creates the array to store the seat assignments.
char flight[rows][seats];
//This function displays the seating chart for the flight
int display()
{
cout << "Displaying the current seating assignments for the flight." << endl;
cout << "The '*' symbol means the seat is available and 'X' means it is not." << endl;
cout << " A " << "B " << "C " << "D " << "E " << "F " << endl;
for(int i=0; i < rows; i++)
{
cout << "Row " << i+1 << " ";
for(int j=0; j < seats; j++)
{
cout << flight[i][j] << " ";
}
cout << endl;
}
}
//This function allows the user to assign their seat.
int assign()
{
int type;
cout << "To begin making your seat assignment please select your ticket type." << endl;
cout << "1. First Class" << endl;
cout << "2. Business Class" << endl;
cout << "3. Economy Class" << endl;
cout << "Please select 1, 2, or 3 from the menu." << endl;
cin >> type;
int fcrow;
string fcseat;
if(type == 1)
{
cout << "You selected First Class" << endl;
cout << "Please review available First Class Seats." << endl;
cout << " A " << "B " << "C " << "D " << "E " << "F " << endl;
for(int f = 0; f < 2; f++)
{
cout << "Row " << f+1 << " ";
for(int g = 0; g < seats; g++)
{
cout << flight[f][g] << " ";
}
cout << endl;
}
cout << "Please enter in the desired row (1 or 2)" << endl;
cin >> fcrow;
cout << "Please enter in the desired seat (A-F)" << endl;
cin >> fcseat;
cout << "You selected Row " << fcrow << " Seat " << fcseat << endl;
int fcsi;
if(fcseat == "A")
{
fcsi = 0;
}
if(fcseat == "B")
{
fcsi = 1;
}
if(fcseat == "C")
{
fcsi = 2;
}
if(fcseat == "D")
{
fcsi = 3;
}
if(fcseat == "E")
{
fcsi = 4;
}
if(fcseat == "F")
{
fcsi = 5;
}
flight[fcrow-1][fcsi] = 'X';
cout << "Displaying Updated Flight Seating Chart" << endl;
return display();
}
int bcrow;
string bcseat;
if(type == 2)
{
cout << "You selected Business Class" << endl;
cout << "Please review available Business Class Seats." << endl;
cout << " A " << "B " << "C " << "D " << "E " << "F " << endl;
for(int h = 2; h < 7; h++)
{
cout << "Row " << h+1 << " ";
for(int k = 0; k < seats; k++)
{
cout << flight[h][k] << " ";
}
cout << endl;
}
cout << "Please enter in the desired row (3-7)" << endl;
cin >> bcrow;
cout << "Please enter in the desired seat (A-F)" << endl;
cin >> bcseat;
cout << "You selected Row " << bcrow << " Seat " << bcseat << endl;
int bcsi;
if(bcseat == "A")
{
bcsi = 0;
}
if(bcseat == "B")
{
bcsi = 1;
}
if(bcseat == "C")
{
bcsi = 2;
}
if(bcseat == "D")
{
bcsi = 3;
}
if(bcseat == "E")
{
bcsi = 4;
}
if(bcseat == "F")
{
bcsi = 5;
}
flight[bcrow-1][bcsi] = 'X';
cout << "Displaying Updated Flight Seating Chart" << endl;
return display();
}
int ecrow;
string ecseat;
if(type == 3)
{
cout << "You selected Economy Class" << endl;
cout << "Please review available Economy Class Seats." << endl;
cout << " A " << "B " << "C " << "D " << "E " << "F " << endl;
for(int l = 7; l < rows; l++)
{
cout << "Row " << l+1 << " ";
for(int m = 0; m < seats; m++)
{
cout << flight[l][m] << " ";
}
cout << endl;
}
cout << "Please enter in the desired row (8-13)" << endl;
cin >> ecrow;
cout << "Please enter in the desired seat (A-F)" << endl;
cin >> ecseat;
cout << "You selected Row " << ecrow << " Seat " << ecseat << endl;
int ecsi;
if(ecseat == "A")
{
ecsi = 0;
}
if(ecseat == "B")
{
ecsi = 1;
}
if(ecseat == "C")
{
ecsi = 2;
}
if(ecseat == "D")
{
ecsi = 3;
}
if(ecseat == "E")
{
ecsi = 4;
}
if(ecseat == "F")
{
ecsi = 5;
}
flight[ecrow-1][ecsi] = 'X';
cout << "Displaying Updated Flight Seating Chart" << endl;
return display();
}
if(type != 1 && type != 2 && type !=3)
{
cout << "Error" << endl;
cout << "The Ticket Type Selected does not exist." << endl;
cout << "Exiting Program" << endl;
cout << ". . . . . . . ." << endl;
exit(13);
return(13);
}
}
//This function allows the user to cancel their seat selection.
int cancel()
{
int canrow;
string canseat;
cout << "We are sorry you wish to cancel your seat assignment." << endl;
cout << "Please enter the row of your seat (1-13)." << endl;
cin >> canrow;
cout << "Please enter the seat letter (A-F)." << endl;
cin >> canseat;
cout << "You selected Row " << canrow << " Seat " << canseat << endl;
int canseati;
if(canseat == "A")
{
canseati = 0;
}
if(canseat == "B")
{
canseati = 1;
}
if(canseat == "C")
{
canseati = 2;
}
if(canseat == "D")
{
canseati = 3;
}
if(canseat == "E")
{
canseati = 4;
}
if(canseat == "F")
{
canseati = 5;
}
flight[canrow-1][canseati] = '*';
return display();
}
//This function allows the user to exit the program.
int close()
{
cout << "Exiting Program" << endl;
cout << ". . . . . . . ." << endl;
exit(11);
return(11);
}
//This starts the main program/menu used to run the functions.
int main()
{
int z = 0;
do
{
//These for loops fill the flight array with '*' to show all seats as empty.
for(int a = 0; a < rows; a++)
{
for(int b = 0; b < seats; b++)
{
flight[a][b] = '*';
}
}
z = z+1;
}while (z = 0);
//This creates the LCV and sets it equal to 0 to run the do loop.
int x = 0;
do
{
//These four lines explain what the program does to the user.
cout << "Welcome to Flight Seat Assigner" << endl;
cout << "This program will allow you to select an available seat for your flight" << endl;
cout << "based on the ticket type and available seats." << endl;
cout << "You also can cancel a seat assignment or display the seating chart." << endl;
//This line tells the user to pick a menu option.
cout << "Please select from the following menu to begin." << endl;
//These lines tell the user what the menu options are.
cout << "1. Display Flight Seating Assignments" << endl;
cout << "2. Select a Seat" << endl;
cout << "3. Cancel a Seating Assignment" << endl;
cout << "4. Exit Program" << endl;
//This creates a variable to store the user's menu selection.
int menu = 0;
//This stores the user's selected menu option.
cin >> menu;
//This if statement runs if the user selects the first menu option.
if(menu == 1)
{
//This line runs the display function.
return display();
}
//This if statement runs if the user selects the second menu option.
if(menu == 2)
{
//This line runs the assign funciton.
return assign();
}
//This if statement runs if the user selects the third menu option.
if(menu == 3)
{
//This line runs the cancel function.
return cancel();
}
//This if statement runs if the user selects the fourth menu option.
if(menu == 4)
{
//This line runs the close function.
return close();
}
//This else statement runs if the user enters a non-menu option.
else
{
//These lines explain the user's meu selection mistake and closes the program.
cout << "Error" << endl;
cout << "The option selected does not exist." << endl;
cout << "Please enter a number between 1-4 when using the menu." << endl;
cout << "Closing Program" << endl;
cout << ". . . . . . . ." << endl;
exit (12);
return(12);
}
//This while statement controls when the do loop runs.
}while (x = 0 && x != 0);
}
Here is the code just for the do-while loop in question.
do
{
//These four lines explain what the program does to the user.
cout << "Welcome to Flight Seat Assigner" << endl;
cout << "This program will allow you to select an available seat for your flight" << endl;
cout << "based on the ticket type and available seats." << endl;
cout << "You also can cancel a seat assignment or display the seating chart." << endl;
//This line tells the user to pick a menu option.
cout << "Please select from the following menu to begin." << endl;
//These lines tell the user what the menu options are.
cout << "1. Display Flight Seating Assignments" << endl;
cout << "2. Select a Seat" << endl;
cout << "3. Cancel a Seating Assignment" << endl;
cout << "4. Exit Program" << endl;
//This creates a variable to store the user's menu selection.
int menu = 0;
//This stores the user's selected menu option.
cin >> menu;
//This if statement runs if the user selects the first menu option.
if(menu == 1)
{
//This line runs the display function.
return display();
}
//This if statement runs if the user selects the second menu option.
if(menu == 2)
{
//This line runs the assign funciton.
return assign();
}
//This if statement runs if the user selects the third menu option.
if(menu == 3)
{
//This line runs the cancel function.
return cancel();
}
//This if statement runs if the user selects the fourth menu option.
if(menu == 4)
{
//This line runs the close function.
return close();
}
//This else statement runs if the user enters a non-menu option.
else
{
//These lines explain the user's meu selection mistake and closes the program.
cout << "Error" << endl;
cout << "The option selected does not exist." << endl;
cout << "Please enter a number between 1-4 when using the menu." << endl;
cout << "Closing Program" << endl;
cout << ". . . . . . . ." << endl;
exit (12);
return(12);
}
//This while statement controls when the do loop runs.
}while (x = 0 && x != 0);
Sorry the code is so long, but the program is almost finished. I just need to fix the loop not restarting as far as I can tell.
BessieTheCow's comment led me to the correct solution for the program. I changed the functions to void and removed the returns for the most part. Now the program works great. Thank you for all of your help everyone. It is much appreciated by this programming noob.

while loop if and else

What the code does is ask the user which card he wants and prints out a statement depending on which card is chosen.
My aim is to loop back to the card select function if numbers other than 1,2 and 3 are entered.
There is also a for loop which allows this process to go around multiple times.
What is the best way and how can I do this?
int CardSelect() {
cout << "Enter 1 for hearts" << endl;
cout << " " << endl;
cout << "Enter 2 for diamonds" << endl;
cout << " " << endl;
cout << "Enter 3 for joker" << endl;
return 0;
};
int main() {
for (int i = 1; i <= 5; i++) {
CardSelect();
int cardchoice;
cin >> cardchoice;
cardchoice = CardSelect();
if (cardchoice == 1) {
cout << "You got hearts" << endl;
loop = false;
} else if (cardchoice == 2) {
cout << "You got diamonds" << endl;
loop = false;
} else if (cardchoice == 3) {
cout << "You got joker" << endl;
loop = false;
} else {
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
}
}
}
Change return type of CardSelect() to void, since your simply printing some statements in that function:
void CardSelect()
{ // Your cout statements
}
Call that in main(), and use a switch case for your cardchoice variable.
If you want to keep running the switch statement till you get a valid input, put everything in an inifinte loop (such as a while(1)) and set an exit condition by setting a boolean to true (set it to false initially) and using break when condition is satisified, to get out of the loop:
int main()
{
while(1)
{
bool valid = false;
CardSelect(); // call to your function
int cardchoice;
cin >> cardchoice;
switch(cardchoice)
{
case 1:
cout << "You got hearts" << endl;
valid = true;
break;
case 2:
cout << "You got diamonds" << endl;
valid = true;
break;
case 3:
cout << "You got joker" << endl;
valid = true;
break;
default:
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
break;
} if(valid) break;
}
}
you should not call cardchoice = CardSelect();.
This call is overwriting cardchoice with 0. Remove this call.
You print values to see what is happening. Its a good way of learning.
Hope this will help.
First, what you are looking for is continue, second you need to get rid of this line which makes no sense :
cardchoice = CardSelect();
as it erases user input
int CardSelect() {
cout << "Enter 1 for hearts" << endl;
cout << " " << endl;
cout << "Enter 2 for diamonds" << endl;
cout << " " << endl;
cout << "Enter 3 for joker" << endl;
return 0;
};
int main() {
for (int i = 1; i <= 5; i++) {
CardSelect();
int cardchoice;
cin >> cardchoice;
if (cardchoice == 1) {
cout << "You got hearts" << endl;
}
else if (cardchoice == 2) {
cout << "You got diamonds" << endl;
}
else if (cardchoice == 3) {
cout << "You got joker" << endl;
}
else {
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
}
}
}

C++ Switch statement loop back to menu

I'm struggling to get my switch statement to go back to the start after an option is selected, to allow the user to input another option. I removed all the code from the switch cases just to cut it down a bit.
Thanks
int main() {
char tab = '\t';
int input;
bool menu = true;
FlightSystem f;
vector <Aircraft> allAircraftList_{};
std::string flightNumber, airline, aircraftType, gridReference;
int groundSpeed, altitude, heading;
const int MaxAlt = 60000, MinAlt = 0, MaxSpeed = 800, MinHeading = 0, MaxHeading = 360;
regex fNumber{ "([a-z]{2}([a-z])?[0-9]([0-9])?([0-9])?([0-9])?([0-9])?)" };
do {
std::cout << "#########################################################" << endl;
std::cout << "#Flight Control Simulation#" << endl;
std::cout << "#########################################################" << endl;
std::cout << "" << endl;
std::cout << tab << "1. Add Aircraft" << endl;
std::cout << tab << "2. List All Aircraft" << endl;
std::cout << tab << "3. List All Cruising Aircraft" << endl;
std::cout << tab << "4. Number of Aircrafts in Sector" << endl;
std::cout << tab << "5. Remove Aircraft" << endl;
std::cout << tab << "6. Change Heading" << endl;
std::cout << tab << "7. Get Heading" << endl;
std::cout << tab << "8. Change Altitude" << endl;
std::cout << tab << "9. Get Altitude" << endl;
std::cout << "" << endl;
std::cout << "---------------------------------------------------------" << endl;
std::cout << "Please enter an option, between 1-9:" << endl;
std::cin >> input;
switch (input) {
case:
break;
default:
cout << "Your selection must be between 1 and 9" << endl;
}
return 0;
} while (input != 9);
}
Here is my advice. Use a while loop. do-while loop in this case is unnecessary.
here's how it can be used (i made a simple program that enters a number, you can modify it accordingly, just replace my code with your switch statements)
#include<iostream>
using namespace std;
int main()
{
int x;
bool repeat = true;
while(repeat)
{
cout<<"enter a number"<<endl;
cin>>x;
cout<<"do you want to enter another number (y/n)"<<endl;
char ch;
cin>>ch;
if(ch=='y'||ch =='Y')
continue;
else
repeat = false;
}
cout<<"you entered "<<x;
}