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

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

Related

C++; Is there a way to get my Switch function to reject a valid and invalid answer together?

So I've been learning how to use the "switch" statement recently. I decided to do some practice exercises. The code I show in my sample code below is one I came up with myself as a solution for a "Cola Machine" beginner exercise I found on a website "cplusplus". The exercise problem text can be found as a multi-line comment at the top of my code. Though, I did decide to try to make my code do more than what was required of the exercise.
For the most part, this code works exactly how I want it to. At first I even struggled to figure out how to get the code to repeat the user input in the line switch (cin.get()), if they had entered an invalid answer, but I solved this issue by nesting the "switch" statment inside of a "for" statement, for (int x = 0; x < 1; x++), and having the invalid answers decrement the counter ( x--; ). Not sure if that's a practical solution, but it's the one I came up with.
The only time my program doesn't run as intended is when a multiple character input that contains both valid answers and invalid answers is entered into the program (i.e. "-1" or "17"). The latter example outputs the statement for only the valid part of the answer, the statement for case '1', where as the former example outputs the statements for invalid answers and valid answers, so the default case and case '1'. Example for input "-1"
I'm wondering if that's just a problem that is inherent to using using "switch" statements in general, or if there's a practical solution I've yet to learn. I'm using a book to learn how to code, "C++ How To Program" by H.M. Deitel/P.J. Deitel, and they had given me a sample code for a letter grade counting program that can be found in my previous question on here. And I found that this same problem occurs in that sample code.
I'd be happy to hear any and all solutions, thank you ! :)
/* Write a program that presents the user w/ a choice of your 5 favorite beverages (Coke, Water, Sprite, ... , Whatever).
Then allow the user to choose a beverage by entering a number 1-5.
Output which beverage they chose.
>> Modify the program so that if the user enters a choice other than 1-5 then it will output "Error. choice was not valid, here is your money back." */
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
int main()
{
string drink1 = "Water", drink2 = "Coke", drink3 = "Pepsi",
drink4 = "Orange Juice", drink5 = "Powerade";
string choose_text = "\n\nChoose your preferred drink: ", chosen_text = "\nYou have chosen: ";
cout << "1.) " << drink1.append(17 - drink1.length(), ' ') << "2.) " << drink2.append(17 - drink2.length(), ' ')
<< "3.) " << drink3.append(17 - drink3.length(), ' ') << "4.) " << drink4.append(17 - drink4.length(), ' ')
<< "5.) " << drink5.append(17 - drink5.length(), ' ') << choose_text;
for (int x = 0; x < 1; x++) {
switch (cin.get()) {
case '1':
cout << chosen_text << drink1 << endl;
break;
case '2':
cout << chosen_text << drink2 << endl;
break;
case '3':
cout << chosen_text << drink3 << endl;
break;
case '4':
cout << chosen_text << drink4 << endl;
break;
case '5':
cout << chosen_text << drink5 << endl;
break;
case '\n': case ' ':
x--;
break;
default:
cout << "\nError. Choice was not valid.\nPlease enter an option 1 - 5." << choose_text;
x--;
break;
}
}
return 0;
}
You can do this:
int answer;
cin >> answer;
That will retrieve an integer value from the user instead of a single character. That solves part of your problem.
Now, let's look at your loop. Ick. Let's try this:
bool keepWorking = true;
do {
keepWorking = false;
int answer;
cin >> answer;
switch (answer) {
...
set keepWorking to true on the bad answers
}
} while (!cin.eof() && keepWorking);

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

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.

Why is control + P leading to infinite loop in C++ (Visual Studio)?

I've been programming for a while (in Prolog, Scheme, and a little bit in C), but I recently decided to brush up on my C++ knowledge. I solved a problem that was meant to illustrate vectors. It was essentially a project to create a database that creates a vector to temporarily store the various games that the user inputs into it, and removes the ones they don't want. The code itself is running fine, not as pretty as scheme or Prolog could do it, but it works.
However, I accidentally typed "Control P" into the first prompt of the program and I got the strangest result: it started an infinite loop. I tried it again with "Control Z" and I got the same result. I haven't tried any other key combos, but I imagine that some others could be found. It's not a super worrying problem, but I am curious to know why it's doing this. Is it something about C++, or is it just Visual Studio? Anyway, here's the source:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
cout << "Welcome to the Cpp Games Database!";
int x = 0;
string game = "";
vector <string> games;
vector <string>::const_iterator iter;
while (x != 4){
cout<< "\n\nPlease choose from the list bellow to decide what you want to do:\n";
cout<< "1. Add Games to the Database.\n"
<< "2. Remove Games from the Database.\n"
<< "3. List all the Games.\n"
<< "4. Exit.\n"
<< "\n(Type the number of your choice and hit return)\n";
cin >> x;
switch (x){
case 1:
game = "";
do{
cout << "\nPlease Input a Game (type esc to exit): ";
cin >> game;
games.push_back(game);
} while (game != "esc");
games.pop_back();
break;
case 2:
game = "";
do{
cout << "\nPlease input the game you would like to remove(or type esc to exit): ";
cin >> game;
iter = find(games.begin(), games.end(), game);
if(iter != games.end())
games.erase(iter);
else cout << "\nGame not found, try again please.\n";
} while (game != "esc");
break;
case 3:
cout << "\nYour Games are:\n";
for (iter = games.begin(); iter != games.end(); iter++)
{
cout << endl << *iter << endl;
}
break;
default: break;
}
}
return 0;
}
Since you are not inputting valid data for cin it is stuck there waiting for the data to be reprocessed or discarded for new input. You need to check your input and only accept valid data. Essentially cin is keeping the original data it's given and continuously trying to process it.
Always verify your input and discard it if it's invalid.
Here is another answer on the same problem for some more insight (with source).
https://stackoverflow.com/a/17430697/1858323

What Is Causing Infinite While Loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am creating a game for two people to play to guess a number, I had it working with an if statement, but if player 2 gets it wrong I would like them to be able to guess again until they get it right. I decided to use a while loop, but I am getting an infinite loop of text, what can I do to stop it?
Here is my code: (I have commented out the if statement while working on the while loop)
#include <iostream>
using namespace std;
int main() {
int player1; //Number variable 1
int player2; //Number variable 2
cout << "Player 1 type in a number between 1 and 100: "; //Asks player to enter a number
cin >> player1;
system("CLS");
cout << "Player 2 guess the number between 1 and 100: "; //Asks guess a number
cin >> player2;
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
}
system("pause");
system("pause"); //Keeps window on screen
return 0;
}
Also any feedback on how to make my code better would be highly appreciated.
You got two things wrong
The braces for the while loop.
You are not reading user input again in the loop.
Modify the loop as below..
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
cin >> player2;
}
The problem is that within the while loop you never change the value of player1 or player2. Hence if they are unequal the first time they will be forever unequal and the code will loop infinitely. To fix this you need to move the code which changes the values into the body of the loop. Hence the user has a chance to change the values.
do {
cout << "Player 2 guess the number between 1 and 100: "; //Asks guess a number
cin >> player2;
if (player2 == player1)
cout << "Correct!" << endl;
else
cout << "Wrong, try again" << endl;
} while(player2 != player1)
If you don't use an open brace after the while statement it only refers to the following expression.
Additionally, after the while you are not reading data from the user again, so how do you expect player2 to ever change?
In terms of code organisation it would be better to set player2 to something obviously invalid, like -1, and have the while at the beginning, without the previous read and if statement so it doesn't have to be special cased.
Try this...
do
{
cout << "Player 2 guess the number between 1 and 100: "; //Asks guess a number
cin >> player2;
} while (player2 != player1)
Your curly brackets are in the wrong position and you never read input from the player after the first time.
if you change it like this, the second player will be asked again.
....
while(player1 != player2){
cout << "Player 2 guess the number between 1 and 100: ";
cin >> player2;
}
In addition, you should add some basic error handling, for example checking if the cin.error() flag is set.
Your while has no brackets, which makes the line right after it repeat forever!
Put the cout and cin for player 2 guess inside a do-while loop and then verify the condition.
cout << "Player 1 type in a number between 1 and 100: "; //Asks player to enter a number
cin >> player1;
system("CLS");
do {
cout << "Player 2 guess the number between 1 and 100: ";
cin >> player2;
} while(player2 != player1);
In
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
}
Nothing in the loop ever changes player2 nor player1, so if the condition player2 != player1 was true, it will remain true.
The loop
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
}
is an endless loop, because the variables player2 and player1 are not changed inside of the loop. If the while condition is true when entering the loop, it will stay true forever.
UPDATE:
To allow player2 to guess repeatedly, and hence change the number that he guessed and get out of the while loop, add cin >> player2; after the cout statement:
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
cin >> player2;
}