User Input

Learn to get the user’s input in the console.

What we have

We have set up taking the number of rounds from the user and the game’s introduction. This is our inventory of already created functions:

// Function to display game introduction and rules
void displayIntroductionAndRules() {
    cout << "Welcome to Rock-Paper-Scissors game!\n" << endl;
    cout << "The rules of the game are simple:" << endl;
    cout << "1. Rock beats scissors" << endl;
    cout << "2. Scissors beats paper" << endl;
    cout << "3. Paper beats rock" << endl;
}

// Function to get number of rounds
int getRound() {
    int rounds;
    cout << "How many rounds would you like to play? ";
    cin >> rounds;
    return rounds;
}

In this task, we have to ask for user input to select one of the three options.

What now?

We can create a function that takes user input and returns it. We can follow these steps to complete this task:

  • Create a variable to store the user’s choice.
  • Take the input from the user.
  • Return the variable.

Try it yourself

Write your code in the code widget below and click the “Run” button to execute your code.

If you’re unsure how to do this, click the “Show Hint” button.

Get hands-on with 1400+ tech skills courses.