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

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")
{
...
}

Related

Why does my function get read, but become an infinite loop? [duplicate]

This question already has answers here:
If statement runs through whether conditions are met or not
(4 answers)
Closed 2 years ago.
Hello I'm having a problem where when I call my function after the user enters "Y" to start the game, the cout gets read but it becomes an infinite loop. It works just fine when you enter "N" or something thats not supposed to be entered. I am using a header file called functions to well, put all the functions if that has anything to do with it. I am still in the very early learning stages of programming, and run into so many speed bumps and just not quite sure where to turn. Any help is appreciated. (P.S. I have not yet started on the gameStart() function just because of this problem. That's not whats it's going to be in the end.)
#ifndef FUNCTIONS_H;
#define FUNCTIONS_H
#include <iostream>
using namespace std;
void startScreen()
{
void gameStart();
char answer;
cout << "Welcome to __________\n\n";
cout << "This is my fisrt ever actual program I made out of my own free will lol.\n";
cout << "It is a Text-Based Adventure game. In this game you will make a character,\n";
cout << "and explore the land of Spelet, battling enemies, leveling up, getting loot,\n";
cout << "and learning skills! You do not need to capitalize anything but your character\n";
cout << "name. If a question has (something like this), those are the choices for that \n";
cout << "interaction! Thank you for trying out my terrible little game! :)\n";
cout << "I really hope y'all enjoy it!\n\n";
cout << "Would you like to play?\n";
cin >> answer;
do
{
if (answer == 'Y' || answer == 'y')
{
gameStart();
}
else if (answer == 'N' || answer == 'n')
{
cout << "Program will now close...\n";
system("pause");
exit(0);
}
else
{
cout << "Enter a Y for yes or an N for no.\n";
cout << "Would you like to play?\n";
cin >> answer;
}
}
while (answer != 'N', 'n' || 'Y', 'y');
}
void gameStart()
{
cout << "\n\"BOOM-BOOM-BOOM...\"\n\n" << endl;
}
#endif
maybe you need:
while (answer != 'N' && answer != 'n' && answer != 'Y' && answer != 'y')
The comma operator doesn't do what you think it does. It "discards the result," as my link says.
You want the && operator (AND operator) instead:
while (answer != 'N' && answer != 'n' && answer != 'Y' && answer != 'y');

Don't know how to add loop to my program...?

Okay I was told to write a rock/paper/scissors game using "switch statements." I finished that, but today in class we were asked to add a loop to our existing game.
I understand the basics about for loops and while loops, however I don't understand how to add them to an existing program.
Which one is better to use? And what do I do?
Thanks guys
So again, I understand the basics of for loops and while loops. But I don't understand if there is anything else I need to declare, what I need to input to receive the correct output/loop.
#include <iostream>
using namespace std;
int main()
{ // opening bracket
int game;
cout <<"Let's play Rock, Paper, Scissors \nEnter 1 for rock, 2 for paper,3 for scissors"<< endl ;
cin >> game;
switch(game)
{
case 1:
cout << "You chose rock" << endl;
break;
case 2:
cout << "You chose paper" << endl;
break;
case 3:
cout << "You chose scissors" << endl;
break;
default:
cout<<game << " is not a valid choice"<< endl;
}
} // closing bracket
BELOW IS MY PROFESSOR'S INSTRUCTIONS:
Create the second part of a Rock, Paper, Scissors game. Enhance lab 5 so that the user keeps playing as long as they enter in 'Y'. Make this case sensitve; if they enter a lower case y the game will not continue. If the user enters in anything besides upper case Y the game will end.
Your text must exatly match the examples below:
Example 1 with correct input
Let's play Rock, Paper, Scissors
Enter 1 for rock, 2 for paper, 3 for scissors
2
You chose paper
Would you like to play again (Y for yes, N for no)?
Y
Enter 1 for rock, 2 for paper, 3 for scissors
1
You chose rock
Would you like to play again (Y for yes, N for no)?
N
Example 2 with incorrect input
Let's play Rock, Paper, Scissors
Enter 1 for rock, 2 for paper, 3 for scissors
5
5 is not a valid choice
Would you like to play again (Y for yes, N for no)?
y
Its probably best for you to watch some youtube videos or read up on basics about loops. Anyways, here is a very simple way to understand this
#include <iostream>
int main(){
char choice = 'Y';
//enter this loop since 'choice' equals Y
while(choice == 'Y'){
//run the game
//if they enter anything else other than Y, it will stop the loop
std::cout << "Would you like to play again (Y for yes, N for no)? \n";
std::cin >> choice;
}
return 0;
}
Here is what you have now:
//some code that plays a game
Here is what you want:
while player wishes to continue playing
//same code that plays the game
end while
or alternatively use a for loop but exiting that will be different, you will need to "break" out of it.
You can also make use of infinite loop to make it work.
#include <iostream>
using namespace std;
int main()
{ // opening bracket
int game;
while(1) //you can comment this line and uncomment below line rest all will be same
//for(;;)
{
cout << "\nLet's play Rock, Paper, Scissors \n Enter \"1\" for rock\n Enter \"2\" for paper\n Enter \"3\" for scissors\n **Press any other key to exit from the game." << endl ;
cout << "\nYour option is : ";
cin >> game;
switch(game)
{
case 1:
cout << "You chose rock\n" << endl;
break;
case 2:
cout << "You chose paper\n" << endl;
break;
case 3:
cout << "You chose scissors\n" << endl;
break;
default:
cout << game << " is not a valid choice\n"<< endl;
return 0;
}
}
} // closing bracket

Do-while loop issue: Try to develop a simple game

Well, I'm writing to make a dice game. I tried searching dice game here but none of it seems to answer my question. This isn't a problem about the dice roll thing anyway. It's about the do while loop. I am very new to this site, I just found out about this via Maximum PC Magazine so please bear with me. Also I am new to programming.
Here is my code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
srand(time(NULL));
int userRoll = rand() % 6 + 1 ;
int computerRoll = rand() % 6 + 1 ;
string yesOrNoChoice;
string commandToThrowDie;
do{
cout << "Please enter \"throw\" (lowercase) to roll the die: ";
cin >> commandToThrowDie;
} while(commandToThrowDie != "throw");
do{
cout << "You rolled: " << userRoll << endl
<< "The Computer rolled: " << computerRoll << endl;
if (userRoll < computerRoll){
cout << "You lose. Try again? [Yes/No]: ";
}
if (computerRoll < userRoll){
cout << "You win! Try again? [Yes/No]: ";
}
if (computerRoll == userRoll) {
cout << "It's a draw. Try again? [Yes/No]: ";
}
cin >> yesOrNoChoice;
} while(yesOrNoChoice != "Yes");
system ("pause");
return 0;
}
The problem is that after asking the user to enter a choice at the end of the do-while-loop the program exits loop no matter what I enter, instead of looping back to another throw of the die.
It ends up like this:
I copied your code and it compiled and ran perfectly. Doesn't make sense exactly, but no issues. I say it doesn't make sense since when "Yes" is entered that is what kills it. I believe what you want it while(yesOrNoChoice == "Yes"). Perhaps having it as != was making you think you were getting the wrong behavior? Also, you should be using if, else if, else statements, not just if.

How to end a loop early if a user says to C++

Note: This is a homework assignment.
I am trying to make a program that plays the game Pig! Pig is a game with the following rules:
1. First to get 100 GAME POINTS is the victor.
2. On your turn, you roll a dice. If you get a 1 at any roll, you end your turn and add 0 to your GAME SCORE.
3. If you roll any value other than a 1, you have the option to HOLD or PLAY. If you PLAY, your roll is added to your TURN SCORE and you roll again. If you HOLD, your TURN SCORE is added to your GAME SCORE and the turn passes to the computer.
The game is coming along very easily until I get to the following problem (see code):
int player(){
char PlayAgain = 'Y';
int turn_score = 0;
while (PlayAgain != 'N' || PlayAgain != 'n'){
int dice;
srand(time(NULL));
dice = rand() % 6 + 1;
turn_score = turn_score + dice;
if (dice != 1){
cout << "You rolled a " << dice << "! Would you like to roll again? [Y/N]: ";
cin >> PlayAgain;
if (PlayAgain == 'N' || PlayAgain == 'n'){
/*END TURN AND return turn_score;*/
}
}
if (dice == 1){
cout << endl << "Oops! You rolled a 1! Your turn is ended, and you add nothing to your score.\n";
system("PAUSE");
/*END TURN, NO SCORE ADDED*/
}
}
}
How can I have the program end the loop prematurely (if either the play HOLDS or dice == 1) and return the proper value (if HOLD, return turn_score. Else return 0)? [See two noted sections]
You can use break to get out of a loop. Since you're saying that you want to return "the right value" then you should do something like that:
On the first if clause
if (PlayAgain == 'N' || PlayAgain == 'n'){
/**Game-Specific logic here**/
return turn_score
}
and on the second one:
if (dice == 1){
cout << endl << "Oops! You rolled a 1! Your turn is ended, and you add nothing to your score.\n";
/**Game-Specific logic here**/
cin.get();
return turn_score;
}
A return statement doesn't need to be at the end of the function and more than one return statements can co-exist inside the same function
Rather then correcting your code I would like to make you clear about what actually is needed here.
Ever heard of break; statement.Let us understand with a simple example
see the following code snippet where your program is taking input from the user,it keeps on taking input from the user until you press 'A'
char var;
while(true)
{
cin>>var;
if(var=='A') break;
}
Now in this program,the while loop is set to true and will keep on running and taking input from the user,and the if statement will not run until the user have entered 'A'. AND the moment 'A' is given as the input,break will take the control out of the while loop for you.
How about having your 'return' statement (with the proper value depending on the case) inside your loop? This will break both the loop and the function, but returning the value you needed.

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.