Want to go back to a function on if/else statement - c++

Please look at this code, and I will explain:
void GameOver()
{
cout << "\nWelp, you died. Want to try again?" << endl;
cin >> choice;
if (choice == "Yes" || "yes")
{
/*This is where I want the code. I want it to go back to the last
function that the player was on.*/
}
if (choice == "No" || "no")
{
cout << "Are you sure? The game will start over when you open it back up." << endl;
cin >> choice;
if (choice == "No" || "no")
{
cout << "Well, bye now!" << endl;
usleep(1000000);
exit (EXIT_FAILURE);
}
}
return;
}
I would like it so that when I choose "Yes" in the GameOver function, I want an if/else statement that says "if you came from this function, then you will go to that function", you see what I'm saying?
For example, let's say I am in the GameOver function and I came from a FightProcess function. I choose "Yes" then it will go to the Town function.
How would I code that?

First, a statement like this:
if (choice == "Yes" || "yes")
Is coded wrong, and will always evaluate as true. You need to use this instead:
if (choice == "Yes" || choice == "yes")
Or better, use a case-insensitive comparison function, like this:
if (strcmpi(choice.c_str(), "Yes") == 0)
Second, unless you add an input parameter, or use a global variable, GameOver() has no idea who is calling it. So what you want to do does not belong in GameOver() itself to begin with. It belongs in the calling function instead. GameOver() exits the game if the user chooses not to continue. That is all it should do. The calling function should decide how to retry if the game does not exit. For example:
void GameOver()
{
cout << "\nWelp, you died. Want to try again?" << endl;
cin >> choice;
//if (choice == "Yes" || choice == "yes")
if (strcmpi(choice.c_str(), "Yes") == 0)
return;
cout << "Are you sure? The game will start over when you open it back up." << endl;
cin >> choice;
//if (choice == "No" || choice == "no")
if (strcmpi(choice.c_str(), "No") == 0)
return;
cout << "Well, bye now!" << endl;
usleep(1000000);
exit (EXIT_FAILURE);
}
void FightProcess()
{
...
if (defeated)
{
GameOver();
Town();
return;
}
...
}
Or, if Town() is the function that called FightProcess():
void FightProcess()
{
...
if (defeated)
{
GameOver();
return;
}
...
}
void Town()
{
...
FightProcess();
...
}
Or, it might make more sense to have FightProcess() loop instead:
void FightProcess()
{
...
do
{
...
if (won)
break;
GameOver();
...
}
while (true);
...
}
See how things get more flexible when you don't put restrictive logic where it does not belong?

I would recommend using a parameter in the GameOver function. Then you could pass a different parameer each time you want to go somewhere else. For example, call GameOver(1) from function 1 and GameOver(2) from function 2.
This is assuming that returning from GameOver and executing different options in the calling function isn't an option.

Or you can choose to fire a event in FightProcess().
eg:-
void FightProcess(){
...
if( ...){
observer.send("FightProcess"); // or with more information.
//observer.send("FightProcess",Avatar::Killed);
GameOver();
}
}
And in the GameOver() you can query the observer to find what the last event was.

Related

Having to hit enter twice with cin.getline()

I know for a fact similar questions have been asked before but I really can't figure out what's wrong with my code specifically. For some reason if I input "n" I have to press enter twice. But if I input "y", everything works fine and the code moves to the next section. My code is as follows:
do{
try {
if (test) cout << " Re-enter: ";
test = false;
getline(cin, choice);
checkinput(choice);
}
catch (int flag) {
if (flag == 1){ cout << "Error: Input must be y or n."; test = true; }
}
} while (test);
and the checkinput function is as follows:
// function for checking the input of y/n
string checkinput(string c) {
if (c != "Y" && c != "y" && c != "N" && c != "n") {
throw 1;
}
if (cin.fail()) throw 1;
return c;
}
I think you are trying to do too much here. You can simplify this.
There is no need to throw and catch exceptions inside checkinput. Since there is only two cases you can use a boolean. Secondly, you are returning c. I don't know why you are doing that, it isn't being used. You should instead, return a boolean.
checkinput becomes:
bool checkInput(string c) {
if (c.length() > 1)
return false;
return c == "Y" || c == "y" || c == "N" || c == "n";
}
Now you can simplify the do-while and remove the try statement. Additionally, there is no need for the test variable now since we are successfully grabbing any input:
int main() {
string choice = "";
do {
cout << "Enter yes or no (y/n): ";
getline(cin, choice); // or cin >> choice;
bool check = checkInput(choice);
if (!check)
cout << "Error: Input must be y or n." << endl;
} while (true);
}
You may also simplify this further but that will be at the cost of readability. Good luck!

Running a simple C++ function

I've just started learning the basics in C++ and currently am trying to make a program that does a few basic things. The problem I have is occurring in the pasted function below.
At this point it literally does nothing when it runs. All I'm trying to do it make it so the function runs over and over again forever, until the user enters the letter 'q'.
The function must keep running even if the user enters some random string, anything, 'q' is the only keystroke that should stop the loop.
I have tried toying around with 'cin.whatever" and haven't found success. If you have an answer please provide as much explanation as possible. Thank you!
void menu()
{
cin.clear();
cin.ignore();
char quit = 'w';
while (quit != 'q') // while loop to allow the user infinite tries
{
cout << "Which story would you like to play? Enter the number of the story (1, 2, or 3) or type q to quit: " << endl;
cin >> quit;
if (quit < '1' or quit > '3') // make sure the user picks a valid choice
{
cout << "Valid choice not selected." << endl;
}
if (quit == '1')
{
story1(); // run story 1
}
if (quit == '2')
{
story2(); // run story 2
}
if (quit == '3')
{
story3(); // run story 3
}
if (quit == 'q')
{
cout << "good bye" << endl;
break;
}
}
}
Try adding single quotes around your 1,2,3 like you did with the q. The cin is expecting a char to be entered so evaluate it as such. e.g: if (quit == '1')

C++: goto and user input not working together

I am working on C++, and using a basic authentication method using if statements, so what I have here, is when the the input is not the desired combination, it will say Access denied and ask the user if they want to try again or quit. I tried doing this using the goto variable, but it hasn't been working. Help please? (Full code: https://pastebin.com/49LdGgJX)
else {
cout << "Access denied..." << " Try again? (Y/N) >" << flush;
string ask;
cin >> ask;
if(ask == "N" || "n"){
cout << "Shutting down..." << endl;
goto end;
}
else if(ask == "Y" || "y"){
goto restart;
}
else {
cout << "Invalid option." << endl;
goto restart;
}
}
end:
return 0;
Your if statements are wrong as:
if(ask == "N" || "n")
always evaluates to true because the "n" operand always evaluates to true and you are using a logical OR operator. The string literal of "n" decays to const char* pointer whose value is not 0 thus evaluating to true. What you want is:
if(ask == "N" || ask == "n")
and:
else if(ask == "Y" || ask == "y")
That being said don't use goto.
One of the possible break-ups of that code structure into more procedural way (wouldn't dare to call this "object oriented").
You can use similar way to break up menu handling code into separate functions for each option, etc.
If this would be multi-user app, then you may want to store instead of simple true/false full credentials of the user authenticated, like having a structure containing name, code (password probably can be thrown away after authentication to not keep it in memory long, if you don't need it later).
// returns true if user wants to exit
// sets authenticated to true when the Drew user is detected
bool AuthenticateUser(bool & authenticated) {
cout << "Enter your username >" << flush;
...
if (name == "Drew" && ...) {
authenticated = true;
cout << "Access granted. Welcome, " << name << "." << endl;
cout << "Welcome to Database of Drew" << endl;
return false;
}
cout << "Access denied..." << " Try again? (Y/N) >" << flush;
...
return (ask == "N" || ask == "n"); // N = wants to exit
}
// returns true if user wants to exit
bool ProceedWithMenu() {
cout << "1.\tAdd new record." << endl;
cout << "2.\tDelete record." << endl;
...
if (1 == value) {
...
}
if (5 == value) {
cout << "Application quitting... " << endl;
}
return (5 == value);
}
void mainLoop {
bool authenticated = false;
bool exitApp = false;
do {
if (!authenticated) {
exitApp = AuthenticateUser(authenticated);
} else {
exitApp = ProceedWithMenu();
}
// repeat authentication / menu until user decides to quit app
} while (!exitApp);
}
This example is still quite crude and oversimplified, just trying to illustrate power of do {} while, return, and similar. Often also continue and break can be of great help to control the flow of code execution, without any goto and labels.

Code in C++ will not accept no and stop the program

I have tried many things and i can not seem to figure out why this program will not stop the code if you select N when it prompts to try again or not.
I feel as though i had this working earlier, but i can not find any code from when it was working, and i see no reason this should not work. Can anyone help out?
#include <iostream>
using namespace std;
int main ()
{
char color[10];
char reboot, yes_no;
start:
cout << "What color is the light?\n";
cin >> color;
//if the light is Green
if (!strcmp(color, "green")) {
cout << "The light is Green, you may go ahead and drive thru the intersection.\n";
} else if (!strcmp(color, "Green")) {
cout << "The light is Green, you may go ahead and drive thru the intersection.\n";
//if the light is Yellow
} else if (!strcmp(color, "yellow")) {
cout << "The light is Yellow, safely stop at the intersection, or proceed thru.\n";
} else if (!strcmp(color, "Yellow")) {
cout << "The light is Yellow, safely stop at the intersection, or proceed thru.\n";
//if the light is Red
} else if (!strcmp(color, "red")) {
cout << "The light is Red, you need to stop.\n";
} else if (!strcmp(color, "Red")) {
cout << "The light is Red, you need to stop.\n";
}
//non recognised input
else{
cout << "\nYour input was not recognised...Would you like to restart? (Y/N)\n";
cin >> yes_no;
if(yes_no == 'Y'||'y'){
goto start;
}
}
//restart program
restart:
cout << "\nWould you like to run the program again? (Y/N)\n";
cin >> reboot;
if(reboot == 'Y'||'y'){
goto start;
}
return 0;
}
Your condition is not well formed it should be
if( (reboot == 'Y') || (reboot == 'y') )
{
goto start;
}
As it is, it always evaluates to true since 'y' evaluates to true and true || anything always gives true.
Same thing applies to yes_no check.
EDIT Since you are having trouble, I made a simple program to test it more easily, this should work as expected:
#include <iostream>
using namespace std;
int main()
{
char yes_no;
while (true)
{
cout << "Enter 'N or 'n' to quit\n";
cin >> yes_no;
if(yes_no == 'N'|| yes_no == 'n')
break;
}
return 0;
}
These 2 lines looks a bit strange
if(yes_no == 'Y'||'y')
if(reboot == 'Y'||'y')
maybe you meant below instead??
if(yes_no == 'Y' || yes_no == 'y')
if(reboot == 'Y' || reboot == 'y')
Starting with the real reason your code doesn't work - operator precedence and associativity:
reboot == 'Y'||'y'
always returns true, since it's parsed as (reboot=='Y')||'y'. If you want to test if reboot is equal one of the two chars, test it like that: reboot=='Y'||reboot=='y'.
That should fix your code. Although here are some advices:
Don't use the goto statement. You can loop your code using loops (while, for or do while).
If you're using C++, use std::string for storing text, you can then use text=="some Text" instead of testing the output of strcmp.
For future reference on operator precedence, you can always check Wikipedia.

using user input such as YES and NO to control program flow in C++

I'm making a small program that uses a if else statement, but instead of using numbers to control the flow i want to be able to make the control work with with yes and no;
for example:
cout << "would you like to continue?" << endl;
cout << "\nYES or NO" << endl;
int input =0;
cin >> input;
string Yes = "YES";
string No = "NO";
if (input == no)
{
cout << "testone" << endl;
}
if (input == yes)
{
cout << "test two" << endl;
//the rest of the program goes here i guess?
}
else
{
cout << "you entered the wrong thing, start again" << endl;
//maybe some type of loop structure to go back
}
but I can't seem to get any variations of this to work, i could make the user type a 0 or 1 instead but that seems really stupid, i'd rather it be as natural as possible, users don't speak numbers do they?
also i need to be able to simply add more words, for example "no NO No noo no n" all would have to mean no
hopefully that makes some sense
also i would love to make this using a window but i've only learned basic c++ so far not even that and i cant find any good resources online about basic windows programming.
You're not reading in a string, you're reading in an int.
Try this:
string input;
instead of
int input = 0;
Also, C++ is case-sensitive, so you can't define a variable called Yes and then try to use it as yes. They need to be in the same case.
btw, your second if statement should be an else if, otherwise if you type in "NO" then it will still go into that last else block.
First of all, input must be std::string, not int.
Also, you've written yes and no wrong:
v
if (input == No)
// ..
// v
else if (input == Yes)
^^^^
If you want your program to work with "no no no ..", you could use std::string::find:
if( std::string::npos != input.find( "no" ) )
// ..
The same with "Yes".
Also, you could do this to be almost case-insensitive - transform the input to upper-case letters (or lower, whatever ), and then use find.This way, yEs will be still a valid answer.
bool yesno(char const* prompt, bool default_yes=true) {
using namespace std;
if (prompt && cin.tie()) {
*cin.tie() << prompt << (default_yes ? " [Yn] " : " [yN] ");
}
string line;
if (!getline(cin, line)) {
throw std::runtime_error("yesno: unexpected input error");
}
else if (line.size() == 0) {
return default_yes;
}
else {
return line[0] == 'Y' || line[0] == 'y';
}
}
string input;
cin >> input;
if (input == "yes"){
}
else if (input == "no"{
}
else {
//blah
}