How to Build a Guessing Game with C++

RedXIII | June 3, 2021, 4 p.m.

Building a guessing game is a great way to get familiar with any new computer programming language. In this tutorial, we’ll walk you through a C++ program that allows the user to guess a secret number

Our program will pick a secret number at random and the user will get a chance to guess the number. If they choose correctly, we’ll let them know they’ve won the game. Otherwise, we’ll let them know they’ve failed.


We’re assuming you have a C++ compiler installed on your computer. If not, you’ll want to stop now and install a compiler. If you’re on a Windows machine, you can follow our guide to getting started with C++.

Planning the Project

Before getting started with any program, it’s a good idea to plan ahead. Our program is pretty basic, but it still requires several components. 

For starters, we need to generate a random number for the computer to guess. We can do that in C++ using the rand() function.

We’ll also need to get input from the user. That’s a bit trickier because we’ll need to validate the input data as well. 

Lastly, we’ll need to compare the user input to the secret number and let them know if they’ve guessed correctly or not. Using these instructions, we can start building our guessing game.

Loading Libraries

The first thing we need to do is figure out what C++ libraries we’ll need for our program to work. These will be included at the top of the program. Use #include to import a library's header files.


The first library our program needs is iostream. We’ll use this library to handle the basic input and output of our guessing game.

What is a C++ library?

A C++ library includes codes that will be used in many different programs. Typically, a library contains functions and classes that handle a generic operation that many developers are likely to want. For instance, C++ comes with libraries for handling input and output, a common task in many programs.


Building the Main Function

Our Main() function is where our program begins. When we execute the program, the Main() function serves as the entry point.


When the program starts, we want to begin the game. We can do this by calling a function. This function will handle the logic of the game, keeping it outside the Main() function.

#include <iostream>

using namespace std;
void PlayGame();
int main(){
  PlayGame();
  return 0;
}
void PlayGame(){
 // game logic goes here
}


If you were to compile this program and run it, nothing would happen. The next step is to add some interactivity to the code.

Getting User Input

Now that the Main() function is ready to go, we can move on to getting input from the user. The trick here is to make sure we receive valid input. Because our secret number is within a specific range (1-10), we need to make sure the user enters a number that is within this range.

Getting the input is easy. We can use cin to ask the user for a number. Doing so inside a while loop allows us to give the user a second chance to enter a valid number.


To ensure the user gives us a number, we can use stio(). This function is a part of the string library, so we’ll need to include it in our program using #include.

#include <string>


The stio() function will convert the user input to an integer, but we still need to ensure the user gave us a number. What if they try to guess “dog?” What we need is a way to force the user to give us only valid data.

We can do that in a number of ways. The standard way is to use a try-block to ensure that the input data is valid.

Writing the Input Function

Because we’re going to be reusing it, our input code should be inside its own logic. This way, if the player gives us bad input, we can ask them to try again.


We’ll also add a special case for exiting the game. Since our guessing range is between 1 and 10, we’ll let the user enter a “0” to quit the game, otherwise they’ll be stuck playing forever.


Before we can write the function, we’ll have to add some global variables. These will go at the top of the program.

#include <iostream>
#include <string>
using namespace std;
// Global Variables
string s = "10";
int i = 0;

We’ll use a string to keep up with the user input data. An integer will store the user’s guess after we convert it to an int.

We’ll use a string to keep up with the user input data. An integer will store the user’s guess after we convert it to an int. 

In the GetInput() function, we use a try-block to get the user’s guess. We also use conditional statements to handle all the possible cases of user input.

int GetInput(){
  // we'll first try to get an integer
  try {
    cout << "--------------------------------------" << endl;
    cout << "Guess a number 1 - 10, or 0 to quit: " << endl;
    cin >> s;
    i = stoi(s); // convert the string to an int
    // make sure the number is in range
    if(i > 10 || i < 0){
      cout << "Out of range." << endl;
    }
    // getting here means we have a valid number
    else {
        cout << "You guessed " << i << endl;
      }
  }
  catch (invalid_argument const &e){
    cout << "Bad input: invalid_argument thrown" << endl;
  }
  catch(out_of_range const &e){
    cout << "Integer overflow" << endl;
  }
  return i;
}


By wrapping this function call inside a while loop in the PlayGame() function, we’ll ensure the program repeats, asking the user to guess a new number until they quit the game.

void PlayGame(){
  while(s != "0")
  {
    int guess = GetInput();
  }
}


Creating the Win/Lose Scenarios

Now that we’ve finished the GetInput() function, we can move on to creating some random numbers. Before the player can correctly guess the secret number, we need to create one.


In C++, we can create a random number using the rand() function.


int secret_number = 1 + rand() % 10;


This statement will generate a random number between 1 and 10, inclusively. After we’ve generated a secret number, we can test it against the user’s guess.

We’ll handle the win and lose scenarios using a conditional statement.

void PlayGame(){
  while(s != "0")
  {
    int secret_number = 1 + rand() % 10;
    int guess = GetInput();
    if (guess == 0 ){
      cout << "Goodbye" << endl;
    }
    // check for correct guess
    else if (guess == secret_number){
      cout << "You got it! You must be psychic." << endl;
    }
    else {
      cout << "Nope. You aren't at all psychic." << endl;
    }
  }
}


Playing the Game

With MinGW installed, C++ programs can be compiled from the command prompt. The compile process results in an executable file. 


g++ game.cpp


You’ll be left with a file named “a.exe.” Call this file from the command prompt to run the program.


a.exe


You’ll be greeted by our progam’s prompt to enter a number between 1 and 10. If you try to guess the computer’s secret number, you’ll probably lose. I got it on the second try. Maybe I’m psychic... 


Guess a number 1 - 10, or 0 to quit:
4
You guessed 4
Nope. You aren't at all psychic.
--------------------------------------
Guess a number 1 - 10, or 0 to quit:
8
You guessed 8
You got it! You must be psychic.


In Summary

We hope you enjoyed the tutorial. Building a simple guessing game is a great way to tackle the fundamentals of C++. In order to finish the game, you’ll need to learn about using random numbers and asking for user input.

If you’d like a further challenge, rewrite the game so that the user has more than one chance to guess the number. To go even further, tell the user if the number they guessed is too high or low using some conditional statements.

Related Posts

About Us

Learning at the speed of light.

We created Start Prism to help students learn programming. You can find exercises and recent tutorials below.

Topics Quizzes Tutorials

0 comments

Leave a comment