Exit from switch C++ - c++

#include <iostream>
#include <string>
#include <vector>
#include "Player.h"
using namespace std;
void PlayerMenu();
int main() {
int z;
cout << "Please press 0 to see the PLayers Menu. " << endl;
cin >> z;
while (z == 0) {
PlayerMenu();
}
cout << " Now You're Functional Lets get started. ";
};
void PlayerMenu()
{
char ch;
int num;
do {
system("cls");
cout << "\n\n\n\t Player Menu";
cout << "\n\n1 Wallet Balance ";
cout << "\n\n2 Player Invetory";
cout << "\n\n3 To Exit";
cin >> ch;
system("cls");
switch (ch)
{
case '1':
cout << "Your Balance at the moment is ..."<<endl;
cout << "\n";
Bank();
break;
//Show Wallet Balance
case '2':
cout << "Here is your Inventory"<<endl;
cout << "\n";
break;
//Show Inventory
case '3':
cout << " Bye.\n";
break;
//exit i'VE TRIED bREKA BUT it will not go back to the main source code or main method
}
cin.ignore();
cin.get();
} while (ch != '3');//If not 1 or 2 or 3 will ignore it
}
I tried break statements, but the break method will not exit to the main method and run the last following statement. I would like to also run methods inside of the case to case so when a player is selecting 1 it will show the balance of the player. Also when the player inputs a value of 2 it will show a vector of weapons bought.

Use return instead of break to exit from the current function. You then don't need the while (ch != '3'). Instead, you can just use an infinite loop:
while (true) {
// ...
case '3':
cout << " Bye.\n";
return;
}
cin.ignore();
cin.get();
}
You can also use for (;;) instead of while (true), but that's just a stylistic choice.
Also, don't call PlayerMenu() in a loop in main. Just do:
int main()
{
int z;
cout << "Please press 0 to see the PLayers Menu. " << endl;
cin >> z;
if (z == 0) {
PlayerMenu();
}
cout << " Now You're Functional Lets get started. ";
}

break in this context exits the switch. If you wish to exit the function, you will need to return instead.

Your PlayerMenu() function is exiting just fine. The problem is in main():
while (z == 0) {
PlayerMenu();
}
There is nothing in the loop that modifies z, so it never exits. It just keeps going back to the menu forever.
I don't know if you intended to loop there or just test it with an if.

Related

Does anyone know how I could display on a menu that randomly picks up 1 of 6 items (like sword/shield/etc.) and then adds/displays it to a backpack?

This is what I've tried so far including my entire project code for the small class project game. Honestly struggle with arrays and don't even know where to start. The project requirements were to Display a menu (use a switch statement to implement the menu) of actions. Then to display the user has chosen to attack or not attack. Then pick up an item randomly and add the random item to one of 6 items in an array named knapSack. Then display the user picked up the item and its random name along with an option to display the Knap Sacks contents (sorted). I'm actually dropping out of computer science, but if I don't pass this assignment I fail so man I'm begging LMAO.
#include <iostream>
#include <string>
#include <stdio.h>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
using namespace std;
int
main ()
{
//Variables
const double stepForest = 50;
const double stepDungeon = 100;
const double stepHouse = 4000;
const double stepMaze = 6000;
//Direction of walking
string North;
string South;
string East;
string West;
//Direction
string direction;
double step;
double steps;
//Asking how many steps
string sSteps;
int nSteps = 0;
//Not allowing negative steps
while (cout << "How many steps are you taking? " << endl
&& !(cin >> nSteps) || nSteps < 0)
{
cin.clear ();
cout << "ERROR: Illegal input!" << endl;
}
//Asking direction user is moving in
cout << "Which direction? (North, West, South, or East) " << endl;
cin >> direction;
//Steps for forest
if (steps >= stepForest && direction == "North");
{
cout << "You have reached the forest. " << endl;
}
//Steps for dungeon
if (steps >= stepDungeon && direction == "South")
{
cout << "You have reached the dungeon. " << endl;
}
//Steps for house
else if (steps >= stepHouse && direction == "East")
{
cout << "You have reached the house. " << endl;
}
//Steps for maze
else if (steps >= stepMaze && direction == "West")
{
cout << "You have reached the maze. " << endl;
}
{
//For menu
int input ();
void output (float);
//Drop down meny bar selections
float result;
int choice, num;
cout << ("Press 1 to attack\n");
cout << ("Press 2 to not attack\n");
cout << ("Press 3 to pick up an item\n");
cout << ("Press 4 to display Knapsack contents\n");
cout << ("Enter your choice:\n");
choice = input ();
//Attack option
switch (choice)
{
case 1:
{
cout << ("You have chosen to attack\n");
cout << ("Your character has attacked\n");
output (result);
break;
}
//No attack option
case 2:
{
cout << ("You have chosen not to attack\n");
cout << ("You do nothing\n");
output (result);
break;
}
//Picking up item option
case 3:
{
cout << ("You have picked up an item\n");
cout << ("The item has been added to Knapsack\n");
//Random array output for knapSack items
char sorteio1[50][11] =
{ "Sword", "Scarf", "Spear", "Knife", "Katana", "Bow" };
int i;
i = rand () % 50;
cout << ("%s\n", sorteio1[i]);
cout << ("The item you picked up was\n"); //This is where I wanted to insert the random
array
cout << (int ());
// Maybe: "knapsack[count] = loot" *****
// loot= randomItems[randomNumber] *****
//Knapsack contents
output (result);
break;
}
case 4:
{
printf ("1.Sword \n");
printf ("2.Scarf \n");
printf ("3.Spear \n");
printf ("4.Knife \n");
printf ("5.Katana \n");
printf ("6.Bow \n");
output (result);
break;
}
printf ("wrong Input\n");
}
}
int number;
scanf ("%d", &number);
return (number);
{
//To quit game
int choice, num;
bool quit = false;
cout << "Would you like to quit (y/n)? ";
cin >> choice;
//If player chooses to quit
if (choice == 'y')
{
cout << "Goodbye you have chosen to quit the game. See you next time! ";
}
else
{
quit = true;
//If player chooses not to quit, but its the end fo the program anyways so
if (choice == 'n')
{
cout <<
"You have chosen not to quit the game. But this is the end anyways! ";
}
quit = false;
return 0;
}
}

Can't get it back to loop. C++

I'm trying to get it back to loop if they enter anything from the choices. everytime I enter 4, it just ends. and if I pick the right one it also ends. Is there anyway I can get it to ask user to input the right one?
void towsoncourse ()
{
cout << "Enter Course: 1 is COSC,2 is ENGL,3 is MATH" << endl;
int course;
bool finish;
bool finishcourse = true;
cin >> course;
while (finishcourse != true)
{
cout << "Enter correct number for course" << endl;
if (course == 1 || course == 2 | course == 3)
{
finish = true;
}
else
{
cout<< "Error: Enter number corresponding to course." << endl;
}
}
switch (course)
{
case 1:
cout << "COSC" << endl;
break;
case 2:
cout << "ENGL" << endl;
break;
case 3:
cout << "MATH" << endl;
break;
default:
cout << "Error: Enter number corresponding to course" << endl;
}
}
int main ()
{
towsoncourse ();
return 0;
}
Not a complete answer, but rather a guide to point the way.
You want to keep reading an input until it is one of 3 possible values. So a good place to read and test the input would be inside a loop, exiting only when the test conditions are met.
while loops test continue criteria before each execution. do loops test continue criteria after each execution. In you case it is necessary to execute at least once.
There were some issues with the code.
1) while (finishcourse != true) condition was wrong. It should be while (finishcourse == true).
2) finish = true; assignment was wrong. It should have been finishcourse = false;
3) cin >> course; should be taken inside the loop. Because if you place it outside, it will lead to infinite loop in case of incorrect entry.
So, Just to ensure readability, I have rewritten the code. I have assumed that it gets back to the loop in case of incorrect entry and in case of correct entry, it terminates.
#include <iostream>
using namespace std;
void towsoncourse ()
{
bool finishcourse = true;
while (finishcourse == true)
{
int course;
cout << "Enter Course: 1 is COSC,2 is ENGL,3 is MATH" << endl;
cin >> course;
switch (course)
{
case 1:
cout << "COSC" << endl;
finishcourse = false;
break;
case 2:
cout << "ENGL" << endl;
finishcourse = false;
break;
case 3:
cout << "MATH" << endl;
finishcourse = false;
break;
default:
cout << "Error: Enter number corresponding to course." << endl;
}
}
}
int main ()
{
towsoncourse ();
return 0;
}

Alternative to goto in nested loops?

This code is working fine, however this whole time I've tried avoiding using the goto statements that you will see in the switch (dice_total) statement.
Without the goto statements, the program will not loop back to the beginning of while (again=='y' || again=='Y'), and instead it keeps looping itself when it reaches the do-while loop.
However, I believe that it is also important to say, that if dice_total is = to the point_total the first time around then the program will function properly, and loop back to the beginning. For example, when the program starts, the first round will generate the point_total, which we will say its 10. Which is a value that will allow the program to continue to the next round, and if the dice_total also gets the same number, 10, the program will say you win, and the loop will work properly. However, if the program reaches the do while loop, and generates a number that isn't 10, but generates a 10 after a few loops, then the program will not loop to the beginning. So what I want to ask, what is wrong with my switch(dice_total) statement, and how can I fix it, to give the program the same effect without using the goto statements?
#include "stdafx.h"
#include <iostream>
#include <random>
#include <string>
using namespace std;
int main()
{
//Declared Variables***********************************
char again = 'y';
int point1;
int point2;
int point_total;
int round_1=1;
int dice1;
int dice2;
int dice_total;
//*****************************************************
//RANDOM SEED******************************************
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int>dist(1, 6);
//*****************************************************
start://TEMPORARY
while (again == 'y'||again=='Y')
{
int round_1 = 1;
system("CLS");
cout << "WELCOME TO THE CRAPS GAME" << endl;
cout << "THROWING ROUND:" << round_1 << " DICES.............." << endl;
point1 = dist(mt);
point2 = dist(mt);
point_total = point1 + point2;
cout << "ROUND: " << round_1 << " First dice is: " << point1 << " and second dice is: " << point2 <<" and the total is:"<<point_total<< endl;
switch (point_total)
{
case 7:
case 11:
cout << "YOU WON CONGRATS PRESS Y TO PLAY AGAIN!!" << endl;
cin >> again;
break;
case 2:
case 3:
case 12:
cout << "YOU LOST, PRESS Y TO TRY AGAIN" << endl;
cin >> again;
break;
default:
do
{
++round_1;
cout << "ROUND " << round_1 << endl;
dice1 = dist(mt);
dice2 = dist(mt);
dice_total = dice1 + dice2;
cout << "THROWING ROUND: " << round_1 << " DICES.............." << endl;
cout << "ROUND 1 DICE TOTAL IS: " << point_total << endl;
cout << "ROUND: " << round_1 << " First dice is: " << dice1 << " and second dice is: " << dice2 << " and the total is:" << dice_total << endl;
switch (dice_total)
{
case 11:
cout << "YOU WON CONGRATS PRESS Y TO PLAY AGAIN!!" << endl;
cin >> again;
goto start;
case 2:
case 3:
case 7:
case 12:
cout << "YOU LOST, PRESS Y TO TRY AGAIN" << endl;
cin >> again;
goto start;
default:
if (dice_total == point_total)
{
cout << "YOU WON CONGRATS PRESS Y TO PLAY AGAIN!!<<endl;
cin >> again;
break;
}//if
else
{
cout << "Going to next round" << endl;
}
}//dice_total
}//do
while (dice_total != point_total);
break;
}//switch point
}//again while
}//main
The problem you're facing is usual when you have too many nested loops in the same function, and is an indicator that you need to refactor parts of your code to be in their own functions.
If you do this, then you have more possibilities to control the flow of your code: in each function you have break and return, and as you can return a custom value, you can use it to determine in the surrounding function if you need to break or return again.
Besides, this gives you the opportunity to put self-explanatory names to your functions, which makes your code clearer for people that look at it for the first time (as it's written, it's so dense that I can't understand it unless I stare at it for some minutes).
An example of what I mean in code:
Before
int main() {
start:
while (a) {
b1();
switch(c) {
case 1:
do {
d();
if (cond) goto start;
} while(e);
break;
}
b2();
}
}
After
int main() {
while (a) {
if (!doStuff1())
break;
}
...
}
bool doStuff1() {
b1();
while (a) {
bool res = doStuff2();
if (res) return true;
}
b2();
...
}
bool doStuff2() {
switch(c) {
case 1:
if (doStuff3()) return true;
}
return false;
}
bool doStuff3() {
do {
d();
if (cond) return true;
} while (e);
return false;
}
How about this design?
bool stop=false;
while(!stop && (again == 'y'||again=='Y'))
{
while(again == 'y'||again=='Y')
{
// ...
break; /* breaks inner while*/
// ...
stop=true;
break; /* breaks inner while, and prevents running outer loop*/
}
}

File access not working

I am watching Bucky's tutorials on C++. He made a program and i did exactly as he did but i cannot get the list to work. I can get the txt file to view the objects on a separate program but this program just doesn't wanna view anything. It works and compiles okay but nothing on the screen once a choice input is entered. Selecting 4 does exit the program but the 1,2,3 options don't bring up anything at all.
Here's the video explaining the program: https://www.youtube.com/watch?v=86rBqzYIbjA&index=68&list=PLAE85DE8440AA6B83#t=3.934331
My code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int getUserData();
void display(int x);
int main(){
int userdata;
userdata = getUserData();
while(userdata =! 4){
switch(userdata){
case 1:
display(1);
break;
case 2:
display(2);
break;
case 3:
display(3);
break;
default:
}
userdata = getUserData();
}
}
int getUserData(){
int choice;
cout << "Enter 1 to view all the neutral items" << endl;
cout << "Enter 2 to view all the helpful items" << endl;
cout << "Enter 3 to view all the harmful items" << endl;
cout << "Enter 4 to exit" << endl;
cin >> choice;
return choice;
}
void display(int x){
ifstream obj;
obj.open("prog2.txt");
string chars;
int powers;
if(x==1){
while(obj>>chars>>powers)
if(powers==0){
cout << chars<<' '<<powers<< endl;
}
}
if(x==2){
while(obj>>chars>>powers)
if(powers>0){
cout << chars<<' '<<powers<< endl;
}
}
if(x==3){
while(obj>>chars>>powers)
if(powers<0){
cout << chars<<' '<<powers<< endl;
}
}
}
This is getting pretty frustrating and any help at all would be highly appreciated!
Your test 'while(userdata =! 4)' is invalid. The 'not is' operator is !=. What the code actually does is while (user data = !4), meaning you're assigning the expression !4 (which is false, hence 0) to userdata. The test condition then evaluates to false and the loop is not entered.

In C++, how can I make cin "cancel" if the return key is pressed?

I'm trying to learn C++ by writing a simple console application. The user navigates the main menu by entering a number stored in a variable which a switch statement then uses to determine what to do. It's pretty simple. :)
The issue that's bugging me is that when the program reaches the cin statement, pressing return without entering a number doesn't "exit" the statement but just bumps it down to the next line. I guess this makes sense, but how can I make it so pressing return with no previous input just "exits" or "cancels" the cin statement?
Below is a shortened idea of what my application sort of looks like:
int main()
{
int mainMenuSelector;
while(mainMenuSelector != 4){
cout << "--- MAIN MENU -----------------" << endl;
cout << "[1] First Option" << endl;
cout << "[2] Second Option" << endl;
cout << "[3] Third Option" << endl;
cout << "[4] Exit Application" << endl;
cout << "-------------------------------" << endl;
cout << "Selection: ";
cin >> mainMenuSelector;
// This is the statement I want to move along from
// if the user presses the return key without entering any input.
switch(mainMenuSelector){
case 1:
doSomething();
break;
case 1:
doSomething();
break;
case 2:
doSomething();
break;
case 3:
doSomething();
break;
}
}
return 0;
}
std::string input;
while (std::getline(std::cin, input) && !input.empty()) { /* do stuff here */ }
You might want to go further and verify that the input is valid, doesn't just have a bunch of spaces, etc...
Pressing enter with no input results in an empty string value.
You can do this (try it and adapt it to your code):
#include <string>
#include <iostream>
using namespace std;
int main() {
string s;
getline(cin, s);
while(s != "") { // if the person hits enter, s == "" and leave the loop
cout << s << endl;
getline(cin, s);
}
return 0;
}
If you're specifically looking for options which use the stream operators (rather than parsing the input yourself), you might consider std::stringstream. For example:
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
void ExampleCaptureInput()
{
int value;
string s;
getline(cin, s);
if (s != "")
{
stringstream sstream(s);
sstream >> value;
}
}