rand() stuck on one integer

Hello all, I have a program where you play a guessing game. It runs properly, besides that the random number is always 42(for me atleast). What do I need to do to make the random number change?

Also, if I wanted to play guess the number multiple times how do I do that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
  #include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;

int main()
{
    ofstream out("GuessMyNumber.out");

    int num, guess, tries = 0;

    num = rand() % 100 + 1;
    
    cout << "Guess My Number Game\n\n";
     out << "Guess My Number Game\n\n";

    do
    {
        cout << "\nEnter a GUESS between 1 and 100:\n";
         cin >> guess;
         out << guess;
         tries++;

        if(guess > num)
          {
            cout << "Your GUESS is TOO HIGH, try again!\n";
             out << "Your GUESS is TOO HIGH, try again!\n";
          }
        else if(guess < num)
          {
            cout << "Your GUESS is TOO LOW, try again!\n";
             out << "Your GUESS is TOO LOW, try again!\n";
          }
        else
          {
            cout << "\nCorrect! It only took " << tries << " guesses!\n";
             out << "\nCorrect! It only took " << tries << " guesses!\n";
          }
    }
    while(guess != num);

    out.close();
    return 0;
}
You have to seed the random number generator.
with rand(), you need to use srand().

e.g. seed based on current time (second): srand((unsigned)time(NULL));
Call srand once at the beginning of your program.

Note that C++11 brings slightly more verbose, but much better random utilities.
https://stackoverflow.com/questions/19665818/generate-random-numbers-using-c11-random-library
Thank you Ganado for the clarity. One other question, how do I make the program ask if the user wants to play again?
Wrap another do-while loop around your current loop which loops based on the user's response. At which point, I would factor out the actual game logic into its own function.

1
2
3
4
5
6
7
8
string response;
do
{
    playgame();

    // (ask player if they want to play again)
}
while (response is to play again);
Last edited on
I did this, but each time I input yes to play again it returns 0 and ends the program? What rookie mistake am I making?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <ctime>
using namespace std;

int main()
{
    ofstream out("GuessMyNumber.out");

    int num, guess, tries = 0;
    string response;
    srand(time(0));
    num = rand() % 100 + 1;

    cout << "Guess My Number Game\n\n";
     out << "Guess My Number Game\n\n";


    while(response == "yes");
    {
            do
        {
            cout << "\nEnter a GUESS between 1 and 100:\n";
             cin >> guess;
             out << guess;
             tries++;

            if(guess > num)
              {
                cout << "Your GUESS is TOO HIGH, try again!\n";
                 out << "Your GUESS is TOO HIGH, try again!\n";
              }
            else if(guess < num)
              {
                cout << "Your GUESS is TOO LOW, try again!\n";
                 out << "Your GUESS is TOO LOW, try again!\n";
              }
            else
              {
                cout << "\nCorrect! It only took " << tries << " guesses!\n";
                 out << "\nCorrect! It only took " << tries << " guesses!\n";
              }

        }
    while(guess != num);

        cout << "Would you like to play again?";
         cin >> response;
    }
out.close();
return 0;
}
Last edited on
What's the value of response the first time you encounter line 21?
It's either yes or no. Oh I need to declare yes or no to response?
Well, with your code the way it is written at the moment, response is default-initialised to "" (the empty string), so it will fail the first test on line 21.

Just initialise it to "yes" if you don't want an input line before then.
Apologies I am not following. I have initialized the yes to
 
string response = "yes";


And the code now doesn't run properly. Do I need to move line 21 altogether? or swap 21 with 47?
Sorry, it's impossible to run your code online because of all your file operations.

Please state what you mean by "doesn't run properly ".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <ctime>
using namespace std;

int main()
{
   // ofstream out("GuessMyNumber.out");

    int num, guess, tries = 0;
    string response = "yes";
    srand(time(0));
    num = rand() % 100 + 1;

    cout << "Guess My Number Game\n\n";
    // out << "Guess My Number Game\n\n";

    while(response == "yes");
    {
            do
        {
            cout << "\nEnter a GUESS between 1 and 100:\n";
             cin >> guess;
            // out << guess;
             tries++;

            if(guess > num)
              {
                cout << "TOO HIGH, try again!\n";
                // out << "TOO HIGH, try again!\n";
              }
            else if(guess < num)
              {
                cout << "TOO LOW, try again!\n";
               //  out << "TOO LOW, try again!\n";
              }
            else
              {
                cout << "\nCorrect! It only took " << tries << " guesses!\n";
                // out << "\nCorrect! It only took " << tries << " guesses!\n";
              }

        }
    while(guess != num);

        cout << "Would you like to play again?";
         cin >> response;
    }
//out.close();
return 0;
}


try to run it now.

What I mean by doesn't run properly with the yes initialized as a value. I'm unable to type anything on the console output. The game never starts.
Remove the semicolon at the end of line 20 (currently your while test).
WOW! Crazy how that one character throws it all off..

How would I make the program run again without initializing response? It seems as if I'm forcing the user to use yes.
You could ask the user if he wants to play right at the start. But he wouldn't have run the program otherwise! I should leave it. Many people like all variables initialised anyway.
unclear question.
if you take out lines 48&49 it will keep playing forever (or until you ctrl/C out )
as it is, if the user types something besides 'yes' it will stop.

if you don't initialize response, you have to change the logic to make up for it not being defaulted to 'yes' which kicks it into the game the first time due to the while response == yes logic. It would be a bit of rework, but its not a good idea: its better to do this as you have it.
Last edited on
Now the issue is:

Each time the correct number is guessed and the user is asked to play again, if you input yes and continue to the next round, the number stays the same, it doesn't reset.

And the counter for the number of guesses also continues increasing rather than reset per new game.
, if you input yes and continue to the next round, the number stays the same, it doesn't reset.

Of course it does, look at where you set the value of num -- before any loop.
Same thing for the number of guesses counter. If you want to reset it after each game, then you have to assign to it.
I do believe it is working 100% correctly. Thank you all for your input and assistance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <cstdlib> // srand / rand
#include <ctime>   // time
#include <cctype>  // tolower

int main()
{
   std::cout << "Welcome to the number guessing game!!!\n";

   // seed the C random generator
   // static_cast to shut up the conversion warning
   srand(static_cast<unsigned>(time(nullptr)));

   char again { 'y' };

   do
   {
      std::cout << "I have picked a number between 1 and 100.\n\n";

      // pick and store the random number
      unsigned numPicked = rand() % 100 + 1;

      unsigned guess    = 0; // stores the number the user guesses
      unsigned guessNum = 0; // stores the number of guesses

      for (guessNum = 0; guess != numPicked; guessNum++)
      {
         std::cout << "What would you like to guess? ";
         std::cin >> guess;

         if (guess < numPicked)
         {
            std::cout << "\nYou guessed too low!!!\n\n";
         }
         else if (guess > numPicked)
         {
            std::cout << "\nYou guessed too high!!!\n\n";
         }
      }
      std::cout << "\nYou guessed it!!!\n"
         << "It took you " << guessNum << " guesses.\n\n";

      std::cout << "Do you want to play again? (y or n) ";
      std::cin >> again;
   }
   while (tolower(again) != 'n'); // tolower forces the char to lower case
}

Welcome to the number guessing game!!!
I have picked a number between 1 and 100.

What would you like to guess? 50

You guessed too low!!!

What would you like to guess? 75

You guessed too low!!!

What would you like to guess? 90

You guessed too high!!!

What would you like to guess? 85

You guessed too high!!!

What would you like to guess? 80

You guessed too high!!!

What would you like to guess? 76

You guessed too low!!!

What would you like to guess? 77

You guessed too low!!!

What would you like to guess? 78

You guessed too low!!!

What would you like to guess? 79

You guessed it!!!
It took you 9 guesses.

Do you want to play again? (y or n) n
Last edited on
Using C++ <random> and <chrono> headers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <random>   // default_random_engine / uniform_int_distribution
#include <chrono>   // system_clock

int main()
{
   std::cout << "Welcome to the number guessing game!!!\n";

   // get a time-based seed for the random engine
   unsigned seed = static_cast<unsigned> (std::chrono::system_clock::now().time_since_epoch().count());

   // create a random engine, seeding it on creation
   std::default_random_engine URNG(seed);

   // set a distribution range (1 - 100)
   std::uniform_int_distribution<int> dist(1, 100);

   char again { 'y' };

   do
   {
      std::cout << "I have picked a number between 1 and 100.\n\n";

      // pick and store the random number
      unsigned numPicked = dist(URNG);

      unsigned guess    = 0; // stores the number the user guessed
      unsigned guessNum = 0; // stores the number of guesses

      for (guessNum = 0; guess != numPicked; guessNum++)
      {
         std::cout << "What would you like to guess? ";
         std::cin >> guess;

         if (guess < numPicked)
         {
            std::cout << "\nYou guessed too low!!!\n\n";
         }
         else if (guess > numPicked)
         {
            std::cout << "\nYou guessed too high!!!\n\n";
         }
      }
      std::cout << "\nYou guessed it!!!\n"
         << "It took you " << guessNum << " guesses.\n\n";

      std::cout << "Do you want to play again? (y or n) ";
      std::cin >> again;
   }
   while (tolower(again) != 'n'); // tolower forces the char to lower case
}

Welcome to the number guessing game!!!
I have picked a number between 1 and 100.

What would you like to guess? 50

You guessed too low!!!

What would you like to guess? 75

You guessed too high!!!

What would you like to guess? 65

You guessed too high!!!

What would you like to guess? 60

You guessed too high!!!

What would you like to guess? 55

You guessed too low!!!

What would you like to guess? 57

You guessed too high!!!

What would you like to guess? 56

You guessed it!!!
It took you 7 guesses.

Do you want to play again? (y or n) Y
I have picked a number between 1 and 100.

What would you like to guess? 50

You guessed too low!!!

What would you like to guess? 75

You guessed too low!!!

What would you like to guess? 90

You guessed too high!!!

What would you like to guess? 85

You guessed too low!!!

What would you like to guess? 88

You guessed too high!!!

What would you like to guess? 87

You guessed too high!!!

What would you like to guess? 86

You guessed it!!!
It took you 7 guesses.

Do you want to play again? (y or n) N
Topic archived. No new replies allowed.