Skip to main content
2 of 3
Took out useless else if statement

Guess the Number In C++

Mind that this is my first actual program in C++ and I tried to prepare for any possible input. Also the reason I included static_cast<void>(generator(range)) is to throw away the first random value because I read on LearnCpp.com that throwing away the first is a common practice to produce more random results. Anyways here is the code, all suggestions are welcome.

#include <iostream>
#include <limits>
#include <random>

bool validateInput(int input)
{
    using namespace std;

    if (1 <= input && input <= 100)
        return true;
    else
        return false;
}

int generateRandomNumber()
{
    std::random_device dev;
    std::mt19937_64 range(dev());
    std::uniform_int_distribution<std::mt19937_64::result_type> generator(1, 100);
    static_cast<void>(generator(range));
    return static_cast<int>(generator(range));
}

bool placement(int input, int target)
{
    using namespace std;
    if (input > target)
    {
        cout << "Guess is too high.";
        return false;
    }

    else if (input < target)
    {
        cout << "Guess is too low.";
        return false;
    }
    else
    {
        cout << "Guess is correct!";
        return true;
    }
}

int main()
{
    using namespace std;
    cout << "You have 7 guesses to guess what number I am thinking of between 1 and 100.\n";
    int winning_num{ generateRandomNumber() };
    static int tries{ 1 };
    do
    {
        int num;
        cout << "\nGuess#" << tries << ": Enter a number -> ";
        cin >> num;
        if (!cin)
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            continue;
        }

        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        
        if (validateInput(num))
            ;
        else
        {
            continue;
        }
        if (!placement(num, winning_num))
        {
            cout << "\nIncorrect!\n";
            ++tries;
        }
        else
        {
            cout << "\nCorrect!\n";
            exit(0);
        }

    }
    while (tries <= 7);
    cout << "\nYou did not guess the number in the alloted amount of guesses :(\nTry Again!\n";


}