0

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;

}
Stacy Doyle
  • 63
  • 2
  • 2
  • 9

5 Answers5

8

[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().

j_random_hacker
  • 50,331
  • 10
  • 105
  • 169
  • I changed my srand() to srand(time(0)); and added #include and this is the error I am getting 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data I am not sure what the issue is now – Stacy Doyle Oct 29 '13 at 02:30
  • @StacyDoyle: It should only be a warning, not an error. The integer type that holds the current time in seconds that `time()` returns is (usually) bigger than the seed that `srand()` expects, but this is one of the few times when we don't mind about a few bits getting lost because all we really care about is the low-order bits -- the ones that change every second. – j_random_hacker Oct 29 '13 at 02:35
  • @StacyDoyle: I've update my answer to include a cast (conversion) telling the compiler that we know about the possible loss of the high-order bits of the time value and we don't mind :) – j_random_hacker Oct 29 '13 at 02:37
  • Do you see another error in my code that would be preventing it from running because it still says fail. – Stacy Doyle Oct 29 '13 at 02:43
  • @StacyDoyle: Does it fail when you compile, or when you run? – j_random_hacker Oct 29 '13 at 02:44
  • When I go to start without debugging(what our teacher has told us to do to run our programs) in the debug tab in visual studios. – Stacy Doyle Oct 29 '13 at 02:49
  • Doing that will try to compile your program, and if it succeeds then it will try to run it. Does compilation succeed, or do you get an error message at that stage (i.e. before the program even starts running)? If you get an error after it's started running (i.e. after it's shown you "Enter a number between 1 and 100"), then what is it exactly? – j_random_hacker Oct 29 '13 at 02:52
  • The compilation is not successful. – Stacy Doyle Oct 29 '13 at 02:54
  • @StacyDoyle: So what error message does it give? You really have to give me some information here! – j_random_hacker Oct 29 '13 at 02:55
  • Sorry it doesn't give me any error message this what it says in the output box: 1>------ Build started: Project: Ch7prob4, Configuration: Debug Win32 ------ 1>Build started 10/28/2013 8:58:15 PM. 1>InitializeBuildStatus: 1> Touching "Debug\Ch7prob4.unsuccessfulbuild". 1>ClCompile: 1> Ch7prob4.cpp 1>LINK : fatal error LNK1104: cannot open file 'c:\users\stacy_000\documents\visual studio 2010\Projects\Ch7prob4\Debug\Ch7prob4.exe' 1> 1>Build FAILED. 1> 1>Time Elapsed 00:00:00.56 ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== – Stacy Doyle Oct 29 '13 at 02:59
  • @StacyDoyle: The error message is "LINK : fatal error LNK1104: cannot open file 'c:\users\stacy_000\documents\visual studio 2010\Projects\Ch7prob4\Debug\Ch7prob4.exe'" and it's from the linker (a step after the compilation, though you can think of it as being part of the compilation). This is almost certainly because you still have a copy of the program running (check Task Manager if you can't find the window). Exit it -- Windows won't let you write a new version of the .EXE file containing your program if it's still running. – j_random_hacker Oct 29 '13 at 03:02
  • @StacyDoyle: Also when you fix that, read drescherjm's comments -- he's noticed other problems in your program's logic. – j_random_hacker Oct 29 '13 at 03:03
  • Ok my program will run now. However when I type in a number and hit enter the statement Enter a number from 1-100 outputs again. – Stacy Doyle Oct 29 '13 at 03:10
  • @StacyDoyle: So what happens instead? Nothing? If so, is the CPU level low or near 100%? If it's near 100%, that means the program is spinning through a loop endlessly. If it's near 0%, that may mean it's waiting for more input. If you keep typing, does the text continue to appear on the screen? – j_random_hacker Oct 29 '13 at 03:13
  • I enter a number press enter and the "Enter a number between 1-100" prints every time until I put in a number the is more than 100 then it prints "Too high try again" "Too low try again" "You got it right in 2 tries Would you like to play again? Enter Y/N" – Stacy Doyle Oct 29 '13 at 03:20
  • 1
    @StacyDoyle: To find this bug, suppose you entered a guess that was too low. Trace out the steps that will happen. In particular, what will happen at the line `while(number>guess);`? – j_random_hacker Oct 29 '13 at 03:24
3

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.

Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82
2

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.

drescherjm
  • 10,365
  • 5
  • 44
  • 64
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.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 1
    -1. This does not solve the problem, you're just turning off the alarm that is telling you that there is a problem! – j_random_hacker Oct 29 '13 at 02:23
  • It solves the compiler error problem, never been asked for doing more than that! – πάντα ῥεῖ Oct 29 '13 at 02:25
  • +1, as this answer actually solves EXACTLY the question the poster was asking, even if the originally posted code has other errors, this issue addresses the question asked. – nhgrif Oct 29 '13 at 02:26
  • 1
    Solving a compiler error by writing bad code does not help the OP. – Jim Rhodes Oct 29 '13 at 02:27
  • @nhgrif That's what I'm tending to aim for in answers, wrong questions are problem of the OP. Sometimes I come up with forward thoughts, but my experience shows that it's usually not worth it ... – πάντα ῥεῖ Oct 29 '13 at 02:29
  • @JimRhodes It helps him in let the compiler/runtime behavior show his **real** errors after fixing. The most things posted here are XY problems by these means. – πάντα ῥεῖ Oct 29 '13 at 02:32
  • 1
    @nhgrif: Is this the kind of answer you like to get to your own questions? The kind that doesn't actually get to the bottom of the underlying problem? – j_random_hacker Oct 29 '13 at 02:32
  • 1
    @g-makulik I am very sorry that I didn't word my question appropriately let me try again I would like to get my program to work if there are errors let me know what they are and possible how to fix them. I hope this clears up any confusion. – Stacy Doyle Oct 29 '13 at 02:34
  • @g-makulik No where did you explain why the compiler was displaying that message so your answer is virtually useless. – Jim Rhodes Oct 29 '13 at 02:34
  • @j_random_hacker I ask different sorts of questions too... the compiler/IDE is usually pretty explicit with what's wrong with my code and rarely do I have to spend much time figuring out compiler errors... – nhgrif Oct 29 '13 at 02:35
  • @StacyDoyle Don't worry! j_random_hacker's answer seems to cover your problems in depth. I'm just defending my simple answer, starting at the very first point of failure. – πάντα ῥεῖ Oct 29 '13 at 02:38
  • @JimRhodes I'm just fixing for concrete questions, don't care about anything else until the next problem appears! That's the way **I** was keep it going the last 30 years ;) (and I love to let newbies hit the wall BTW, experienced the best learning effect from that! If you're just preaching they won't listen!) – πάντα ῥεῖ Oct 29 '13 at 03:02
0

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;
}
ChuckCottrill
  • 4,360
  • 2
  • 24
  • 42