C++ Vid 17 - Little Game Project issue

Aloha All!

I had completed the assignment stated in the title, however, I’m experiencing a weird issue with it going into an infinite loop whenever a char is entered. Anyone have any ideas?

Thanks!

#include <iostream>

using namespace std;

/*
    GAME RULES:
    1) P1 selects random #
    2) P2 guesses #
    3) Game will tell P2 if guess is too high or low
    4) The game will keep track of guess attempts by P2
*/

int main()
{
    int rndnum {};
    int guess {};
    int counter {};

    cout << "Enter random # from 1-99: ";
    cin >> rndnum;

    while (rndnum >= 100 || rndnum <= 0)
    {
        cout << "Please make sure # is from 1-99: ";
        cin >> rndnum;
    }

    cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nThe random # is in!\nNow guess that #\n(Hint: it's btwn 1-99): ";
    cin >> guess;
    counter++;

    while (guess != rndnum)
    {
        if (guess > rndnum)
        {
            cout << "You thought wrong buddy!\nGuess is higher than selected #\nTotal guess count: " << counter << '\n';
            cout << "Guess again: ";
            cin >> guess;
            counter++;
        }
        else
        {
            cout << "You thought wrong buddy!\nGuess is lower than selected #\nTotal guess count: " << counter << '\n';
            cout << "Guess again: ";
            cin >> guess;
            counter++;
        }
    }

    if (guess == rndnum)
    {
        cout << "You are a weener!!! Cungratz!\nTotal guess count: " << counter << endl;
    }

    return 0;
}

First of, your example will accept numbers from 0 to 100 because you check if the number is more/less than equal :wink:
For your other issue, you must check if the number is numeric. You can do this by either accepting string and parsing it as a number or to check if the inputed stream was indeed a number.
For the second case your example would result in something like this:

#include <limits> // You must include the limits header

int main()
{
    int rndnum {};
    int guess {};
    int counter {};

    cout << "Enter random # from 1-99: ";
    cin >> rndnum;
    
    while (cin.fail())
    {
        cout << "Please enter a valid number\n";
        // Clean up the invalid input buffer
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        
        cout << "Enter random # from 1-99: ";
        cin >> rndnum;
    }

    while (rndnum > 100 || rndnum < 0)
    {
        cout << "Please make sure # is from 1-99: ";
        cin >> rndnum;
    }

    /* Rest of the code... */
2 Likes

Thanks so much for your reply!

This took me a while to understand, but I now thankfully know how it works and what’s going on with the code. I ended up changing back to “>= and <=” since it let me enter 0 and 100 the other way. I also studied and implemented the code you gave. Obviously I have lots to learn!

There’s only 1 odd bug that remains, and that’s when an int/char is entered simultaneously (e.g 55ff). It fails properly if something like “hh77” is entered, but if you enter something like “34efg”, it will accept the input of 34 as the value, then enter the while loop for cin.fail(). I don’t understand why, but I assume as I continue learning, the answer will be clear.

Quick question, regarding using “using namespace std”, is it better practice to type out std::cout versus just cout with the namespace?

Below is what I currently ended up coding. If there is any better method, I’m certainly open to suggestions!

#include <iostream>
#include <limits>

using namespace std;

/*
    GAME RULES:
    1) P1 selects random #
    2) P2 guesses #
    3) Game will tell P2 if guess is too high or low
    4) The game will keep track of guess attempts by P2
*/

int main()
{
    int rndnum {};
    int guess {};
    int counter {};

    cout << "Enter random # from 1-99: ";
    cin >> rndnum;

    while (rndnum >= 100 || rndnum <= 0 || cin.fail())
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Please enter valid # from 1-99: ";
        cin >> rndnum;
    }

    cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nThe random # is in!\nNow guess that #\n(Hint: it's btwn 1-99): ";
    cin >> guess;

    while (cin.fail())
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Please enter valid #: ";
        cin >> guess;
    }

    counter++;

    while (guess != rndnum)
    {
        while (cin.fail())
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "Please enter valid #: ";
            cin >> guess;

            if (guess == rndnum)
            {
                    cout << "You are a weener!!! Cungratz!\nTotal guess count: " << counter << endl;
                    return 0;
            }
        }

        if (guess > rndnum)
        {
            cout << "You thought wrong buddy!\nGuess is higher than selected #\nTotal guess count: " << counter << '\n';
            cout << "Guess again: ";
            cin >> guess;
            counter++;
        }

        else
        {
            cout << "You thought wrong buddy!\nGuess is lower than selected #\nTotal guess count: " << counter << '\n';
            cout << "Guess again: ";
            cin >> guess;
            counter++;
        }
    }

    if (guess == rndnum)
    {
        cout << "You are a weener!!! Cungratz!\nTotal guess count: " << counter << endl;
    }

    return 0;
}

While you are learning to code in C++ you don’t have to bother much with that, either was is fine. Namespaces are just a way to separate code parts.

This comes in handy in large programs where you might have different cout functions in different namespaces. At that point you would need to either call them explicitly (using :: ) or call them from different parts of code using their required namespace. :slight_smile:

At this point its more down to preference how you would like to structure your code. it doesn’t effect performance in any way.

1 Like

Got it. THX! :smiley:

Hello, I have managed to do the little game with a for loop and then at the beginning of the video Ivan said: “You have to realise that we cannot do this with a for loop”
Is there any major flaw in the way I solved it?

Thanks in advance for help!

#include

using namespace std;

int main()
{

/*
    the rules:
    1) player 1 selects a random number
    2) player need to guess the number
    3) the game will tell player 2 whether the guess is too low or too high
    4) the game will count the number of attempts the player 2 made

*/
int randomNumber = 0;
int guessedNumber = 0;

cout << "Player 1, please select a random number" <<endl;
cin >> randomNumber;
cout << "Player 2, please guess a number" << endl;
cin >> guessedNumber;
int counter = 0;
for (counter = 1; guessedNumber >randomNumber || guessedNumber < randomNumber; counter++){
    if (guessedNumber > randomNumber){
        cout<<"Too high!"<<endl;
        cout<<"Attempt n.: "<<counter<<endl;
    }
    else if (guessedNumber < randomNumber){
        cout<<"Too low!"<<endl;
        cout<<"Attempt n.: "<<counter<<endl;
    }
    cout<<"Try again!"<<endl;
    cin>> guessedNumber;
    if(guessedNumber==randomNumber){
        cout<<"Congrats! You guessed the number! Number of attempts: "<<counter+1;
    }
}
return 0;

}

1 Like

@Alko89 plus, in the Ivan’s video, the little game is missing the counting of attempts. Could you please show us how it can be incorporated?

Thank you!

Hmmm, this is an interesting solution. I have never seen someone using a for loop like this :smiley:

The solution is actually fine, I have also tried and it works as expected.

It would be easier to read a while loop that loops while the guessed number is not equal to the random number but using a for loop is also doable (like in your example).

All in all good job :raised_hands: I wasn’t expecting something like this :smiley:

The counter works as well, I got the number of attempts after I completed the game. You could also print the number of attempts in each iteration if you’d like. In that case you can remove the final if statement and print the congratulations string outside of the loop before the end of execution.