Simple Number Guessing Game. C++ - c++

I've been trying to make a simple game where the computer generates a random number and you try to guess it. It also stores the amount of guesses you make "tries".
However, when I run the program, it simply prints: "Let's play a game. I'll think of a number 1-100. Try to guess it."
Here's my code:
#include <iostream>
int main()
{
using namespace std;
int the_number;
int guess;
int tries;
the_number = rand() % 101 + 1;
cout << "Let's play a game!";
cout << "I will think of a number 1-100. Try to guess it.";
cout << endl;
cin >> guess;
for (tries = 0; tries++;)
{
if (guess == the_number)
{
cout << "You guessed it!";
cout << "And it only took you: " << tries;
}
else if (guess < the_number)
{
cout << "Higher";
tries++;
}
else if (guess > the_number)
{
cout << "Lower";
tries++;
}
else
cout << "That's not even in range!";
return 0;
}
}
I don't understand why this doesn't work, could someone explain why not?

The reason your program does not print anything after "Let's play a game. I'll think of a number 1-100. Try to guess it." is the way you have written your for loop.
for ( tries = 0; tries++; )
breaks out of the loop without doing anything because tries++ evaluates to 0.
Also, for your program to work correctly, you need to add more code to read guesses. Something like the code below, should work.
for (tries = 0; ; tries++)
{
if (guess == the_number)
{
cout << "You guessed it!";
cout << "And it only took you " << tries << " tries.\n";
break;
}
else if (guess < the_number)
{
cout << "Higher";
cin >> guess;
}
else if (guess > the_number)
{
cout << "Lower";
cin >> guess;
}
}

You can define a couple of variables that will make your code more understandable, something like this :
#include <iostream>
using namespace std;
int main()
{char EndGame = 'N';
int MyNumber = 150 , playerguess;
cout << "I have a number between 1 and 100.\nCan you guess my number ??\nPlease type your first guess.\n?" << endl;
do{
cin >> playerguess;
if (playerguess > MyNumber) {
cout << " Too High. Try again." << endl;
}
else if (playerguess == MyNumber) {
cout << "Excellent ! You Got It ! \n If you want to exit press Y" << endl;
cin >> EndGame;
break;
}
else {
cout << " Too Low. Try again." << endl;
}
} while (1);
return 0;
}
This will make the number equal to 150. Each time the user inputs a value, the console will determine whether it is higher, lower or equal to the number.
If you want instead to make it a random number each time, you can simply use the <random> library and use the module operator with a number like 100 or 101. Then, you can add 1; this will generate only positive integers.

You should use while loop here, not for:
while (the_number != guess)
{
//
//
}
And try using the new <random> header instead of rand() function:
#include <random>
std::random_device rd;
std::default_random_engine engine(rd());
std::uniform_int_distribution<int> uniform_dist(1, 100);
the_number = uniform_dist(engine);

Your for loop is wrong (it needs 3 things: initialization, check condition and the todo step after each loop.
For example:
for (tries = 0; tries < 5; tries++)
Also you loop the guessing part, but you forget to ask the user for a new number. I would suggest to move the cin << guess into the for loop.

Related

How to prompt user to re-loop the whole program?

I want the user to choose between playing the game again or ending the program, however when prompted, if they press 'y' the same thing gets repeated over and over instead of the whole program from the very beginning. I've tried while loops, do/while loops, if statements, rearranging the code, but nothing has worked. Any advice?
#include <iostream>
#include <string>
using namespace std;
int main(){
string animal = "fish";
string guess;
char choose = 'Y' ;
int count = 0;//keeps a running total of how many times the user
has guessed an answer.
int limit = 5;//allows user to guess only 5 times, otherwise
they loose the game.
bool out_of_guesses = false;//to check whether the user has run
out of guesses.
cout << "I am thinking of an animal.\n" << endl;
do{
while(animal != guess && !out_of_guesses){//Nested while
loop inside main loop to keep track of how many tries the user has
attempted and to validate their answers.
if(count < limit){
cout << "Can you guess what animal I am thinking of?: ";
getline(cin, guess);
count++;
if(animal != guess){
cout << "\nHmm, nope. That's not the animal I'm
thinking of." << endl;
if(count > 2 && count <5){
cout << "I'll give you a hint. It lives in
water." << endl;
}
}
}
else{
out_of_guesses = true;
}
}//End nested while loop
if(out_of_guesses){
cout << "\nI'm sorry, but you are out of guesses." <<
endl;
}
else{
cout << "\n*** Good job! You guessed the correct animal!
***" << endl;
cout << "\t\t><)))º> ❤ <º)))><\t\t" << endl;
}
//The do-while loop is there to ask the user if they wish to
play the game again.
cout << "Would you like to try again?(y/n): ";
cin >> choose;
if(choose == 'N' || choose == 'n')
break;
}while(choose == 'Y' || choose == 'y');
return 0;
}
The bool out_of_guesses = false; must be in-between while(true) and while(animal != guess && !out_of_guesses), and not outside the first while loop. Because our while loop condition is always false, and then it does enter it.
You should also reset your guess variable in-between those 2 loops, else same thing could happen (false while loop) in case of the answer is found.
Here the code with some refactoring/review, which I used the guess as upper case to handle any typography of the answer. I also removed the out of guess variable to use the count and limit one instead.
#include <iostream>
#include <string>
#include <cctype>
int main()
{
const std::string animal = "FISH";
const int limit = 5;
do
{
std::cout << "I am thinking of an animal.\n";
int count = 0;
std::string guess;
while(animal.compare(std::toupper(guess)) != 0 && count < limit)
{
std::cout << "Can you guess what animal I am thinking of?: \n";
std::cin >> guess;
count++;
if(animal.compare(std::toupper(guess)) != 0)
{
std::cout << "\nHmm, nope. That's not the animal I'm thinking of.\n";
if(count > 2)
{
std::cout << "I'll give you a hint. It lives in water.\n";
}
}
}
}//End nested while loop
if(count >= limit)
{
std::cout << "\nI'm sorry, but you are out of guesses.\n";
}
else
{
std::cout << "\n*** Good job! You guessed the correct animal! ***\n";
std::cout << "\t\t><)))º> ❤ <º)))><\t\t\n";
}
char choose = 'Y' ;
std::cout << "Would you like to try again?(y/n): ";
std::cin >> choose;
if(std::toupper(choose) == 'N') break;
} while(true);
return 0;
}

What is wrong with my do...while logic, and continue logic?

I'm new to stackoverflow, and also somewhat new to programming, so please don't mind my poor formatting of the code. I have two problems with my code.
My continue statement, which I'm using to continue the loop if the player types 'y' or 'Y', doesn't work. It terminates the program after only getting the guess correctly, which leads me to:
2.My continue counter goes past 0 without stopping, and I just can't see my error in the logic of the program.
I can't see the problems with my logic.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <ctime>
#include <random>
using namespace std;
int getNumber(); //random number prototype
double getScore(); //gets score
int chances = 7; //chances to guess with
int main()
{
int guess = 0,
random;
char retry = 'y'; //initialize retry to 'y'
cout << "This is a random number guessing game. " << "You will be guessing between 1-100."
<< "You have 7 chances. Good luck! \n \n" << endl;
random = getNumber(); //give the function a variable
do
{
cout << random << "\n" << "\n";
chances--;
cout << "Enter your guess: ";
cin >> guess;
if (guess == random)
{
cout << "You have won the game! " << "Your score was: " << getScore();
cout << "Would you like to retry? (Y or N): ";
cin >> retry;
if (retry == 'y' || retry == 'Y')
{
chances = 7;
guess = 0;
getNumber();
continue; //player can retry the game
}
else if (chances == 0)
{
cout << "You have no chances left. Retry? (Y or N): ";
cin >> retry;
if (retry == 'y' || retry == 'Y')
{
chances = 7;
guess = 0;
getNumber();
continue;
}
}
return 0;
}
else if (guess != random)
cout << "You got it wrong. \n" << "You have: " << chances << " chances left" << endl << endl;
else
cout << "Incorrect Input. Please type a number." << endl << endl;
} while (guess != random);
return 0;
}
int getNumber()
{
unsigned seed = time(0); //seed the random number
srand(seed);
int randNum = rand() % 10 + 1; //random number in the range of 1-10
return randNum;
}
if (retry == 'y' || 'Y')
This is incorrect logic, which is why your code does not work the way you want it to. You want it to be:
if (retry == 'y' || retry == 'Y')
Fix this logic error in your other if-else statements as well.
You'll wanna take a look at this
Your continue statement is jumping to the end and checking the condition, guess != random, which evaluates to false and exits the do while. What you need to do is reset guess to a value such as 0 so that the condition does evaluate to true.

Simplify code for an in-class demo

For a technical writing class I will be leading and having the rest of the class (on the school computers with Visual Studio 2013) participate in making a a simple guess game program. I am trying to make it as straight forward as possible and easy to understand as many of my classmates are not programmers.
Is there anything I can make simpler or easier to follow?
using namespace std;
int main(){
char response = 'y';
while (response != 'n'){
srand(time(NULL));
int guess = -1;
int answer = (rand() % 100) + 1;
while (guess != 0){
cout << "Guess a number between 1 and 100. Guess 0 to quit game." << endl;
cin >> guess;
if (guess == 0){
break;
}
else if (guess == answer){
cout << "Correct!" << endl;
break;
}
else if (guess < answer){
cout << "Too low, guess again!" << endl;
}
else {
cout << "Too high, guess again!" << endl;
}
}
cout << "Play again? (y/n): ";
cin >> response;
}
}
Consider dropping the "play again" or drop the "Guess 0 to quit". In fact, drop the "quit" because the Ctrl-C or close-button of the terminal are already there.
Rename answer to something less confusing (pick or secret) and make it const.
Extract a function for the "voodoo" to generate a random number. Makes it more legible!
Turn the while into a do {} while so you don't have this unintuitive check response != 'n' before anything ever happened at all!
Same for while(guess!=0). Except, you can lose the redundant condition altogether. You already had break there...
Lose the else if where break already made the branch redundant.
Make a polite comment about missing error handling... So people don't sue you when their programs runs haywire :)
Also, write it incrementally, so do e.g.
#include <iostream>
using namespace std;
void play_round();
int main() {
srand(time(NULL));
char response;
do {
play_round();
cout << "Play again? (y/n): ";
cin >> response;
} while (response != 'n');
}
int pick_random(int from, int to) {
return (rand() % (to-from+1)) + from;
}
void play_round() {
const int secret = pick_random(1, 100);
do {
cout << "Guess a number between 1 and 100: ";
int guess;
cin >> guess;
if (guess == secret) {
cout << "Correct!" << endl;
break;
}
} while (true);
}
And then elaborate adding
if (guess == 0) {
break;
}
And eventually
if (guess < secret) {
cout << "Too low, guess again!" << endl;
}
if (guess > secret) {
cout << "Too high, guess again!" << endl;
}
Note how the branches are independent!
Optionally elaborate, doing:
int pick_random(int from, int to) {
return (rand() % (to-from+1)) + from;
}
and use pick_random(1, 100) etc :)

I've know idea where to look, maybe it's an infinite loop? (C++, using VS2012) [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Well, I'll introduce myself first. I'm Ben, a 17-years old 'game-programmer' from the Netherlands who just has begun to program in C++ (started about a month ago, but programming for a year right now) (and I'm using Microsoft Visual Studio 2012 as compiler). Now, I am 'learning it myself' but I still do use a book and that book is called 'Beginning C++ Through Game Programming, Third Edition' by Michael Dawson.
I just did finish with chapter two and the last excersize was: "Write a new version of the Guess My Number program in which the player and the computer switch roles. That is, the player picks a number and the computer must guess what it is."
Here follows the code of the 'Guess My Number' Program:
// Guess My Number
// The classic number guessing game
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0))); //seed random number generator
int secretNumber = rand() % 100 + 1; // random number between 1 and 100
int tries = 0;
int guess;
cout << "\tWelcome to Guess My Number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
if (guess > secretNumber)
{
cout << "Too high!\n\n";
}
else if (guess < secretNumber)
{
cout << "Too low!\n\n";
}
else
{
cout << "\nThat's it! You got it in " << tries << " guesses!\n";
}
} while (guess != secretNumber);
return 0;
}
Now, I was busy with thinking, programming testing and it just wouldn't work.
It seems I got stuck with such a infinite loop. But I can't find the problem.
Here's the code, and other ways to fix this are welcome, just keep in mind that I don't know a lot of the language. ;)
// Guess My Number 2
// The classic number guessing game with a twist
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
int secretNumberComputer = rand() % 100 + 1;
int secretNumberPlayer;
int triesPlayer = 0;
int triesComputer = 0;
int guessPlayer;
int guessComputer;
int tooHighPlayer;
int tooLowPlayer;
int correctPlayer;
int tooHighComputer;
int tooLowComputer;
int correctComputer;
int selectNumberIncorrect;
int lowerGuessComputer = 101;
int higherGuessComputer = 0;
cout << "Welcome to Guess My Number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guessPlayer;
++triesPlayer;
tooHighPlayer = (guessPlayer > secretNumberComputer);
tooLowPlayer = (guessPlayer < secretNumberComputer);
correctPlayer = (guessPlayer == secretNumberComputer);
if (tooHighPlayer)
{
cout << "Too high!\n\n";
}
else if (tooLowPlayer)
{
cout << "Too low!\n\n";
}
else if (correctPlayer)
{
cout << "\nThat's it! You got it in " << triesPlayer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctPlayer);
cout << "Now it's time for you to pick a number and then the computer will guess.\nEnter a number between 1 and 100: ";
do
{
cin >> secretNumberPlayer;
selectNumberIncorrect = (secretNumberPlayer > 100 || secretNumberPlayer < 1);
if (selectNumberIncorrect)
{
cout << "\nHey, that isn't a number between 1 and 100! Please pick a number that is: ";
}
else
{
break;
}
} while (selectNumberIncorrect);
guessComputer = (rand() < lowerGuessComputer && rand() > higherGuessComputer);
cout << "\n\nNow the computer is going to try to guess your number:" << endl;
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
tooHighComputer = (guessComputer > secretNumberPlayer);
tooLowComputer = (guessComputer < secretNumberPlayer);
correctComputer = (guessComputer == secretNumberPlayer);
lowerGuessComputer = (rand() % 100 + 1 && rand() < guessComputer);
higherGuessComputer = (rand() % 100 + 1 && rand() > guessComputer);
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
}
else
{
cout << "Error, check code!\n\n";
}
do
{
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctComputer);
if (triesComputer < triesPlayer)
{
cout << "You lost against the computer!\n\n";
}
else if (triesComputer > triesPlayer)
{
cout << "You won!\n\n";
}
else
{
cout << "It's a tie!\n\n";
}
cout << "Thank you for playing! Goodbye!" << endl;
return 0;
}
In this block you aren't checking the computer's guess for correctness (assigning correctComputer), so the loop continues forever, unless it guessed correctly the first time.
do
{
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctComputer);
Your second do loop never recalculates the computer's guess.
i.e. you have the computer guess one number before the do loop, then in the loop you keep checking if that one guess is too high or too low, never recalculating its value. It'll obviously never end.
You need to do the computer's guess calculation inside the second loop.
EDIT
Also, this logic is incorrect:
lowerGuessComputer = (rand() % 100 + 1 && rand() < guessComputer);
higherGuessComputer = (rand() % 100 + 1 && rand() > guessComputer);
The guess will always be 0 or 1 because the result of the right-hand-side operation is a boolean. In fact, I don't know what you're trying to do there. You're performing && between an integer and a boolean. I also don't understand why you are calculating two different guesses - you should calculate one number within the range of the higher/lower parameters you were given.
In addition to what Kevin Tran wrote, please check the valid input type for cin.
Imagine someone typing characters instead of integers.
so
cin >> guessPlayer;
can be written as
if (cin >> guessPlayer) {
// Do you logic here
}
else {
cout<<"Enter numbers only. :)";endl;
continue;
}
Hope this helps.
Instead of analyzing the code you posted which has numerous flaws, let's just think about what your program has to do: The user will pick a random number, and the computer will try to guess that number.
So, your program flow should go like this:
The computer picks a random number. It prints it out and asks the user to choose if the number is too high, too low or correct. (i.e. by asking the user to type '1' if too high, '2' if too low or '3' if it's right).
If the user types '3' then obviously you're done.
If it's too high, the computer picks a new random number (smaller than it's last guess) and tries the above logic again.
If it's too low, the computer picks a new random number (greater than it's last guess) and tries the above logic again.
Now let's try and implement some code that implements the above:
using namespace std;
int main()
{
int range_low = 0; // The number the user picked is greater than this
int range_high = 100; // The number the user picked is smaller than this
srand(static_cast<unsigned int>(time(0)));
do
{
// We want to generate a random number between range_low and range_high. We do this
// by generating a random number between zero and the difference of "low" and "high"
// adding it to low and adding one more.
int guess = range_low + ((rand() % (range_high - range_low)) + 1);
cout << "I'm guessing your number is " << guess << "... how did I do?" << endl
<< " [1: too high, 2: too low, 3: you got it!] ";
// Now let's see how we did...
int choice;
cin >> choice;
if(choice == 3)
{
cout << "Be amazed at my psychic powers! For I am a computer!" << endl;
break;
}
if(choice == 2)
{
cout << "Hmm, ok. I was sure I had it. Let's try again!" << endl;
range_low = guess;
}
if(choice == 1)
{
cout << "Really? Ok, ok, one more try!" << endl;
range_high = guess;
}
} while(true);
return 0;
}
Here are two exercises for you to improve the above:
First, try to compare the logic of this code against the logic of your code and see where your code differs - try to understand why it was wrong. It will help to try to execute the program using pen and paper, just like you were a computer that understood C++.
Second, try to add code to ensure that the computer never guesses the same number twice.

while loop acting up... not doing what it should for some reason

I have this code for a simple Dice throwing program with betting units and everything... you bet, if you get it right you get the amount u bet times the amount of dice you chose... if you're wrong but by a little (in the range of the number you picked +- the number of dice u picked) you don't lose anything, and if you're really off you lose...
I have a while loop that basically keeps 2 things in mind: as long as the user either has BUs or if they didn't type "no" or "No" for the try again... but for some reason it just doesn't work... lol. any ideas why? the betting system works, it recognizes that betting.currentBU == 0, but the while loop just won't react lol.
#include <iostream>
#include <string>
#include <cstdlib>
#include <time.h>
#include <limits>
using namespace std;
struct Dices{ // structure containing all the dice related integers
int dice;
int total;
int choice;
} Dices = {0,0,0};
struct betting{ // structure containing all the betting integers
int currentBU;
int bettedBU;
} betting = {100, 0};
int DiceThrow(int dicechoice, int totalnum){ // a method for the dice being rolled
for(int i=1; i <= dicechoice;i++){
totalnum = totalnum + (rand() % 6 + 1); //total number, repeated by the loop for every dice
}
return totalnum;
}
int winningbet(int dicea, int cBU, int bBU){ // in case the user guesses it right
std::cout << "Congratulations, you got it right! \n";
cBU = cBU + (dicea * bBU); // give him money...
return(cBU);
}
int losingbet(int dicen, int totaln, int choicen, int cBU2, int bBU2){ //in case the user guesses wrong
if(choicen > (totaln+dicen) || choicen < (totaln+dicen)) // checks how wrong he is, if he's too off, he loses BUs
cBU2 = cBU2-bBU2;
else
std::cout << "you we're so close, you don't lose any BUs! \n"; //if he was really close, just let him know he was close
return(cBU2);
}
int main(){
string decision; // decision if they want to keep playing or not
srand ( (unsigned int)time(NULL) );
while(decision != "no" || decision != "No" || betting.currentBU != 0) // makes sure of the decision AND that he still has BUs
{
Dices.total = 0;
std::cout << "how many dice would you like to use? ";
std::cin >> Dices.dice;
std::cout << "how many How many BUs are you betting?(" << betting.currentBU << " BUs left) ";
std::cin >> betting.bettedBU;
if(betting.bettedBU > betting.currentBU){ // if he doesn't have enough BUs
std::cout << "Sorry, you don't have that many BUs...";
std::cout << "Want to try again with a different amount?(Yes/No) ";
std::cin >> decision;
}
else{
std::cout << "guess what number was thrown: ";
std::cin >> Dices.choice;
Dices.total = DiceThrow(Dices.dice, Dices.total);
if(Dices.choice == Dices.total){
betting.currentBU = winningbet(Dices.dice, betting.currentBU, betting.bettedBU);
std::cout << "Want to try again?(Yes/No) ";
std::cin >> decision;
} else{
std::cout << "Sorry, the number was " << Dices.total << "... better luck next time \n" ;
betting.currentBU = losingbet(Dices.dice, Dices.total, Dices.choice, betting.currentBU, betting.bettedBU);
if(betting.currentBU > 0){
std::cout << "Want to try again?(Yes/No) ";
std::cin >> decision;
}
}
}
}
if(betting.currentBU == 0){
std:cout << "sorry, you ran out of BUs...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
else{
std::cout << "your final BU count is: " << betting.currentBU << "\n";
std::cout << "Thanks for playing, see you next time! (Press ENTER to terminate...)";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
return 0;
}
isn't it supposed to be:
while(decision != "no" && decision != "No" && betting.currentBU != 0)
We need to check if decision not equal to "no" AND not equal to "No" AND the currentBU not equal to 0
Your test is while (A || B || C), which will loop as long as ANY of those three things are true. Since decision can't be equal to both "no" and "No" at the same time, at least one of those two not-equals tests will always be true, so the loop will loop forever...