Stacy Doyle
Stacy Doyle

Reputation: 63

C++ Random number guessing game

I have to write a program that will run a random guessing game. The game is to be numbers from 1-100, the guesser gets 20 tries and at the end is supposed to be asked if they would like to play again. There also has to be multiple options for print outs if the guesser is to high or low. I have part of my program done I know I still need to add the other options for print outs but right now my issue is that when I try to run what I have it says successful but then there is an error that says that the variable "number" is being used without be initialized. I am not sure what to do to get it initialized apparently. (I am new to C++) I have updated my program and am now having a different issue. My program runs but if the guess is lower than the number it prints Too high try again and Too lower try again but when the number is too high it just prints Too high try again. I also noticed that when the user chooses to play again the tries counter is not resetting with the game. One last thing I have to add more messages for when they win, lose and are asked to play another game and I have to use random number to choose among them. SO any advice on the best route to do that would be great

#include <iostream>
#include <iomanip> 
#include <ctime>
using namespace std;
char chr;

int main()
{
srand(time(NULL));                                           //the function that generates random numbers
int number=rand()%100+1;                                     //the range of the random numbers
int guess;                                                   //The guess is stored here
int tries=0;                                                 //The number of tries stored here
   char answer;                                                 //The answer to the question is stored here
answer='y';                  

while(answer=='y'||answer=='Y') 
{
    while (tries<=20 && answer=='y'|| answer=='Y')
    {
    cout<<"Enter a number between 1 and 100 "<<endl;          //The user is asked for a guess
    cin>>guess;                                               //The guess is stored here
    tries++;                                                 //Adding a number for every try
    if(guess==0||guess>100)                                  //If statement that produces an error message if user enters a number out of the peramiters
    {
     cout<<"This is not an option try again"<<endl;          //Error message
    }

    if(tries<20)                                            
    cout<<"Tries left: "<<(20-tries)<<endl;                   //Output to let the user know how many guess they have left

    if(number<guess);                                         //if the guess is to high
    cout<<"Too high try again"<<endl;                         //This message prints if guess it to high

    if(number>guess)                                          //if the guess is to low
    cout<<"Too low try again"<<endl;                          //This message prints if the guess is to low

    if(number==guess)                                          //If the user guesses the number
    {
     cout<<"Congratualtions!! "<<endl;                          //Message printed out if the user guesses correctly
     cout<<"You got the right number in "<<tries<<" tries"<<endl;  //Lets the user know how many guess they used
     answer = 'n';
    }
    if(tries >= 20)                                               //If the user uses all their guesses
    {
    cout << "You've run out of tries!"<<endl;                      //The message that prints when a user is out of guesses
    answer='n';
    }
    if(answer=='n')
    {
     cout<<"Would you like to play again?  Enter Y/N"<<endl;       //asking if play would like to play again
     cin>>answer;                                                  //Store users answer
     if (answer=='N'|| answer=='n')                                //if the user says no
     cout<<"Thanks for playing!"<<endl;                            //This message prints out if they choose not to play again

    else
        number=rand()%100+1;                                        //This starts the game over if they choose to play again
    }

    }
    }

cin>>chr;
    return 0;

}

Upvotes: 0

Views: 19369

Answers (5)

drescherjm
drescherjm

Reputation: 10857

One problem that I see is that you are picking a new random number for each user guess. This is wrong.

To fix this you should put the

number=rand()%100+1;

line before the do while loop that loops asking for guesses.

A second problem is the condition on that loop is not correct. You should loop until number == guess not number > guess and put the both couts that tell the user if the guess is high or low inside the loop and increment your tries inside the loop as well.

Also you probably want to have an outer do while() loop for the question that asks you to play again instead of this loop being after the loop that waits till the user gets the right number.

Upvotes: 2

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Initialize your variables (always!!) before using them, otherwise you're calling for undefined behavior (or even coppiler errors) within any operations with these!

int number = 0;
int guess = 0;
int tries = 0;
char answer = '\0';

NOTE (for downvoters, doubting commenters):
Of course this answer doesn't tell, how to get the srand(number>0); statement right for the desired result (i.e. initializing number with a more appropriate value than 0), but it solves the compile time error asked for in first place, and is good advice for any other scenario, resulting in a similar compiler error (warning). Getting number initialized with an appropriate value to pass to srand() seed method to get the right results expected at runtime, is a completely different question and should be asked as such.

Upvotes: 1

Tristan Brindle
Tristan Brindle

Reputation: 16824

The problem the compiler is warning you about is with these two lines:

int number;
//...
srand(number>0);

Here, you haven't given the variable number an initial value, so it's uninitialised -- you have absolutely no way of knowing what the value might be at this point. In fact, it's likely to change every time you run your programme. Next you're asking whether the mystery value is greater than zero -- it might be, it might not, but you just don't know. It's mystery behaviour, which is what the compiler is warning you about.

Now of course, you're trying to initialise the random seed, so having this mystery behaviour might be what you're after! But unfortunately even that isn't going to work as it stands.

In C++, the expression number>0 is boolean, that is, the result of the expression is either true or false. But the srand() function takes an unsigned int as it's argument, so the compiler has to convert the bool to an unsigned, and it does so by changing false to 0, and true to 1 (probably: I believe it's technically up to the implementation). So no matter what the initial value of number, your random seed is only going to have one of two possible values -- not very random at all!

Better would be to use a random seed based on something (relatively) unpredictable. It's common for non-cryptographic needs to initialise a seed based on the current time. Something like:

#include <ctime>

std::time_t now = std::time(0);
srand(static_cast<unsigned>(now));

would be fine.

Upvotes: 3

ChuckCottrill
ChuckCottrill

Reputation: 4444

May I suggest using the gettimeofday function, as a way to provide a seed to your random function?

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
//clock_t times(struct tms *buffer);
int
main(int argc, char **argv)
{
    int a;
    struct timeval _wall;
    gettimeofday( &_wall, NULL ); //(_wall.tv_sec,_wall.tv_usec);
    srand(_wall.tv_usec);
    a = rand() % 100 + 1;
    printf("%d\n",a);
    return 0;
}

Upvotes: 0

j_random_hacker
j_random_hacker

Reputation: 51226

[EDIT: Added cast to get rid of compiler warning.]

As Jim Rhodes said in a comment, the problem is with the line

srand(number>0);

srand() is used for initialising the random number generator, so it doesn't make sense to call it with number>0, or even with number at all. It wants a "seed" value, that should be different every time you run the program. A common way to get such a seed is by using the system time:

srand(static_cast<unsigned int>(time(NULL)));

You might need to #include another header to get access to time().

Upvotes: 8

Related Questions