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

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.

Related

C++ Random string array If statement only outputs one answer

This is my first ever piece of code that ive developed independently and ive run into an issue. Ive Googled the issue and no prevail. I'm making a Rock Paper Scissors game and I have an input where you choose either Rock Paper or Scissors, after you choose, the program randomly outputs either Rock Paper or Scissors, now my issue is with the If statements after the random output, it only selects:
{
cout << ", you lose! Do you want to play again? (Yes / No)";
}
Whereas, this is my code here:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
// yn = yes / no
string yn;
cout << "Do you want to play Rock, Paper, Scissors? (Yes / No) ";
cin >> yn;
if (yn == "Yes")
{
// rps = rock paper scissors
string rps;
cout << "Choose, Rock, Paper, or Scissors\n";
cin >> rps;
if (rps == "Rock")
{
// Randomizer
srand(time(0));
string rpslist[3] = { "Rock", "Paper", "Scissors " };
int rpsnumber = rand() % 3;
cout << "I choose: " << rpslist[rpsnumber];
if (rpslist[1] == "Rock")
{
cout << ", we draw! Do you want to play again? (Yes / No)";
}
if (rpslist[2] == "Paper");
{
cout << ", you lose! Do you want to play again? (Yes / No)";
}
if (rpslist[3] == "Scissors")
{
cout << ", you win! Do you want to play again? (Yes / No)";
}
}
I would like to point out a few things. The most important part that might fix your issue is the 3rd and 4th one. But do read all of them, I think it would be important to know.
1) When you check the elements of an array, you always start at index 0. So in this case, "Rock" would be corresponding to rpsList[0], Paper would be corresponding to rpsList[1], so on and so forth. So when you say if(rpsList[1] == "Rock") this is clearly wrong because rpsList[1] is Paper.
2) 1201ProgramAlarm has pointed this out, you have a semicolon after the if statement for paper.
3) Your if statements should be replaced with if-else-if statements instead. if(rpList[0] == " Rock) ... else if(rpList[1] == "Paper"). What happens is if you have individual if statements, it's going to check every if statement even if the conditions are false. Doing an else if statement after your first if statement will allow you to skip the redundant checks as soon as you find any of the statements to be true.
4) Your if statements do not do anything with the random number previously generated. Instead you're checking if the first element is a Rock, if the second element is Paper, or if your third element is Scissors, in which case they ARE in that sequence since that is how you arranged your string array. Do this instead:
if (rpList[rpsNumber] == "Rock")
{
...
}
else if (rpList[rpsNumber] == "Paper")
{
...
}
else if (rpList[rpsNumber] == "Scissors")
{
...
}

I need help on this C++ yes/no problem while using logical operators

So the problem is: Write a program that prints the question "Do you wish to continue?" and reads the input. If the user input is "Y", "Yes", "YES", then print out "Continuing". If the user input is "N" or "No", "NO" then print out "Quit". Otherwise, print "Bad Input". Use logical operators.
So far this is all the code that I have written. I know that it is not complete, and I do not know what else I need to add to the code.
#include <iostream>
using namespace std;
int main() {
char response;
cout << "Do you wish to continue?" ;
cin >> response;
if (response == 'Y'){
cout << "Continuing";
}
else if (response == 'N'){
cout << "Quit";
}
else if (response != 'N' || 'Y'){
cout << "Bad input";
}
return 0;
}
Update: so I edited my code and it is still giving me a bunch of errors. It's making me frustrated lol. Keep in mind I'm a beginner and we haven't learned loops yet. Sorry for the headache!
#include <iostream>
#include <string>
using namespace std;
int main() {
char response;
string help;
cout << "Do you wish to continue?" ;
cin >> response, help;
if (response == 'Y' || help == "Yes" || help == "YES"){
cout << "Continuing";
}
else if (response == 'N' || help == "No" || help == "NO"){
cout << "Quit";
}
else if (response != 'N' || response != 'Y' || help != "Yes" || help != "YES" || help != "No" || help != "NO"){
cout << "Bad input";
}
return 0;
}
First off I think this is a great start. Sounds like you are new to C++ so here are some suggestions:
1) Your response variable can only contain a character. I would suggest including string and changing the response to take a string from the user for 'Y', "Yes", etc.
2) I suggest wrapping your code in a while loop with an exit condition.
3) Each of your logic branches should include a return integer. This will give the program an exit condition if the logical conditions are met.
I know I haven't given you the answers fully. If you are truly stuck, reply back and we can walk through.
A simple way is to simply convert the user's answer to uppercase or lowercase. By doing this, you can simply use the lower case.
For your loop, you could for example use a "do..while".
#include <iostream>
#include <string>
using namespace std;
int main() {
int stop = 0;
string response;
//Continue until the user choose to stop.
do{
//-------------
// Execute your program
//-------------
cout << "Do you wish to continue? ";
cin >> response;
//-------------
//Convert to lower case
for (string::size_type i=0; i < response.length(); ++i){
response[i] = tolower(response[i]);
}
//-------------
//Check the answer of the user.
if (response.compare("y") == 0 || response.compare("yes") == 0){
cout << "Continuing \n";
}
else if (response.compare("n") == 0 || response.compare("no") == 0){
cout << "Quit \n";
stop = 1;
}
else{
cout << "Bad input \n";
}
}while(stop == 0);
return 0;
}
Like you said in the question, we care about Y,Yes,YES,N,No and NO. For anything else we need to print "Bad Input". Think about how you'd be storing these responses (hint: Sam Varshavchik's answer).
Once you've taken care of extracting user input, you'd want to check what the user actually entered and proceed accordingly. From your question it seems "if else" would do. You need to change the conditionals for your "if else ifs" because
you have 3 conditions for one type of response: Y, Yes and YES need one output - "continuing" while N, No and NO require a different output - "Quit" and for all others we print "Bad input". Think about what your conditionals should be and your if statement should look something like:
if (response == "Y" || response == "Yes" || response == "YES")
and then handle the case accordingly. You'd want to do the same for your No conditions and finally handle the case for all others. I'd suggest having your code like so:
if( conditionals for Yes){
//Code for Yes input
}
else if( conditionals for No){
//Code for No input
}
else{
//Code for all other inputs
}
It is tempting to give you the full answer but think about how your program needs to flow and proceed from there, you've almost got it!
If you have more questions post here and we'd be glad to help!

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

Want to go back to a function on if/else statement

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.

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
}