'How to include a range in C++ guessing game and get code to repeat?

A simple guessing game, but I need instead of simply telling the user that their guess was too high or too low, modify the code such that the user is now given a range of numbers within which the chosen number actually lies.

Precisely,the user is shown a range [low, high] such that lownumhigh.
At the beginning of the game, [low, high] = [0, 100], but as the user makes more guesses, the range is refined and a more accurate range is shown.

An example:
Suppose that num = 78. You first ask the user to make a guess between [0, 100].
The user enters 50 as their guess. So the next range would be [51, 100] since 5178100.
On the other hand, if the user had entered 90, then the next range would have been [0, 89].

Can someone also help me figure out how to get user input so that the code can repeat and they can play again?

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    int num, guess, tries = 0;
    srand(time(0)); 
    num = rand() % 100 + 1; 
    cout << "Guess My Number Game\n\n";

    do {
        cout << "Enter a guess between 1 and 100 : ";
        cin >> guess;
        tries++;

        if (guess > num)
            cout << "Too high!\n\n";
        else if (guess < num)
            cout << "Too low!\n\n";
        else
            cout << "\nCorrect! You got it in " << tries << " guesses!\n";
    } while (guess != num);

    return 0;
}
c++


Solution 1:[1]

I wouldn't recommend you to use rand() and stime since it's a bit old and might give you duplicated numbers, use the modern random library, I do this sometimes to get random number in range:

std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> dist(1.0, 10.0);
float rnd = dist(mt);
unsigned int flt = rnd;

you might want to add inside your code a new random number generation each time user gives input and just replace std::uniform_real_distribution<double> dist(1.0, 10.0); with new range you need 2 random if I understood what you want properly

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marc_s