Building a guessing game is a great way to get familiar with any new computer programming language. In this tutorial, I’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.

I’m 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.

Laying out the main() Function

Our m_ain_() function is where our program begins. When we execute the program, the m_ain_() 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 m_ain_() function.

#include <iostream>
#include <string>

using namespace std;
void playGame();
int main(){
 playGame();
 return 0;
}
void playGame(){
}

If you were to compile this program and run it, nothing would happen. It doesn’t really do anything at this point. The next step is to add some interactivity to the code.

Getting User Input

Now that the m_ain_() 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 a word instead of a number? 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 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.

In the g_etInput_() 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 p_layGame_() 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();
  }
}

#guides-and-tutorials #programming-tutorials #study #learn-programming #c++

How to Build a Guessing Game with C++
1.60 GEEK