Select Page

A program’s execution cycle is composed of three major steps: data input, computing, and data output. Whether your program is a game or personal finance calculator, it needs data on which to perform operations before it can output results to the user or to another program.

In this article, we’ll explain user input in C++ through a programmer’s perspective. We’ll build our own game to illustrate char and string input, integer and float input, and reading from a file. Let’s get started! 

User Input in C++ Explained

There are three different ways of feeding data to a program in C++:

  • Hard-coding: you write the data in the code itself
  • File input: the program accesses a file and extracts data from it
  • Interactive input: the program directly asks the user to provide the required data

After being received, your software performs operations on this data and outputs the end result. If you’re a game developer, your game may ask the player to provide a name for a character or choose its abilities, which can later be altered in-game as the player progresses through the story.

As a C++ developer you’ll need to know how user input works and be able to use it effectively. 

How Does User Input Work in C++?

If you were coding in C++, you’d request the user input with the cin object. cin is part of the standard C++ library and its syntax is as follows:

cin >> variable;

You may already be aware that C++ variables have data types, which determine how much space on memory is required. cin is capable of interpreting whether a user is inputting a character, an integer, or a floating-point number. Let’s look at how each of the available input types for cin work in C++.

String and Char User Input

Let’s say we’re developing a game in which the player first has to build their protagonist. The first thing we’ll ask our player is to give the character a name. We can do so using either char or string input. To begin, let’s declare the variables we need and assign names for the user to pick from:

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main() {

  // Let's set up some default and custom options for character names
  string playerName;
  vector<string> options = {"Frodo", "Bilbo", "Gandalf",
    "Aragorn", "Custom name"};
  char playerAnswer;...

Next, we’ll want the player to either create a name for the character or choose from one of the predefined options:

...
  cout << "Welcome, my friend!" << endl;
  cout << "First, tell me more about you... What's your name?" << endl;

  for (int i=0; i<options.size(); ++i) {
    // Convert an index into a letter starting with A, as letter can be
    // easier to input. So index 0 == 'A', 1 == 'B', and so on.
    char opt = 'A' + i;
    cout << opt << " - " << options[i] << endl;
  }
  // Use cin to get the player's input from the console
  cin >> (playerAnswer);

  // Convert any character input into uppercase, and then
  // convert it back into our index format, so 0 == 'A',
  // 1 == 'B', and so on.
  int choiceIndex = toupper(playerAnswer) - 'A';
...

The code above loops over the options vector and prints out the strings by index, starting at zero and finishing at the end of the vector. The program uses cin to get the user’s choice (A, B, C, D, or a custom name), and then converts the input into uppercase before making it into an index to access the options vector once again.

Now, time to have the program check the input for validity — we don’t want to accidentally accept an invalid option! — and greet the user with their newly chosen name:

... 
  if (choiceIndex >= 0 and choiceIndex < options.size()-1) {
    // The player specified a valid option that's not
    // the Custom name option (it's last in our options list)
    playerName = options[choiceIndex];
  } else {
    cout << "You haven't picked any of the default options." << endl;
    cout << "Enter your custom name below:" << endl << "> ";
    cin >> playerName;
  }

  cout << "Nice to meet you, " << playerName << "!" << endl;
}

The output looks as follows when we pick the Custom name option: 

Welcome, my friend!
First, tell me more about you... What's your name?
A - Frodo
B - Bilbo
C - Gandalf
D - Aragorn
E - Custom name
e
You haven't picked any of the default options.
Enter your custom name below:
> Mithrandir
Nice to meet you, Mithrandir!

Integer and Float User Input

Of course, we’ll also need to give the player the ability to input numbers in our game. Let’s say our player needs to solve a riddle for which they’ll have to input a number as a response. If the player comes up with the right answer, they’ll earn gold coins. First, let’s declare our variables and then present our riddle to the player: 

int main() {

// Let's create variables to store the required data (money, answers etc)
int playerMoney = 500;
float riddleAnswer = 85.5;
float playerRiddleAnswer;

// Let's present the riddle to the player and ask for his answer
cout << "Hello, friend. I've got a challenge for you. ";
cout << "If you succeed, you will get 200 Gold coins. Otherwise, I will keep my money!" << endl;
cout << "Here is the question: If the distance between the Shire and Mordor is 1197 miles,";
cout << "How long will it take Frodo to reach it if he travels at 14 miles/day ?" << endl;
          cout << "> ";
cin >> playerRiddleAnswer;...

Once the player has given an answer, we need to check whether the input is correct. Inputting anything other than a number results in an error that we alert the player to.

..."      //Check if the player enters the data correctly
while (!cin) {
      // Clear the error flag
      cin.clear();
      // Ignore the characters to avoid looping forever
      cin.ignore(numeric_limits<streamsize>::max(), '\n');
      cout << "Error: Please enter a numeric answer, friend!" << endl;
        cout << "> ";
      cin >> playerRiddleAnswer;
}...

This while loop will continuously force the player to retype an answer until they provide a number. Next, our program will check if the user’s answer is correct and if so, will offer them gold. At the end, the player will get a message saying how much gold they now own:

...//Check whether the answer is correct and respond accordingly
if (playerRiddleAnswer == riddleAnswer) {
      playerMoney = playerMoney + 200;
      cout << "Congratulations, you just earned 200 Gold coins." << endl;
}
else {
      cout << "Unfortunately, the answer was " << riddleAnswer << "... You'll do better next time!";
}
cout << "You have " << playerMoney << " Gold coins in your pocket.";
}

This program produces the following output:

Hello, friend. I've got a challenge for you. If you succeed, you will get 200 Gold coins. Otherwise, I will keep my money!
Here is the question: If the distance between the Shire and Mordor is 1197 miles, how long will it take Frodo to reach it if he travels at 14 miles/day ?
85.5
Congratulations, you just earned 200 Gold coins
You have 700 Gold coins in your pocket

Note: While we use float in this example, the outcome would be similar to the above if we needed to use double, int, or any other type of number-based data.

What About Reading From a File?

Most current software read files from either the local computer or a web-based or local server. Our game may need to read a save game file that stores data related to where the player left off after their last session—e.g., how much money they had. 

First, let’s create a save game text file and write data in it:

int main() {
  //First, we create a text file and write save game data in it
  ofstream MyFile("savegame.txt");
  MyFile << 50; // initial amount of gold coins
  MyFile.close();...

Next, we’ll open the save game file and check that there was no issue in opening it:

...   //Now, we read the data from the text file to store it in a variable
  ifstream MySaveGame;

  //Opening the save game file
  MySaveGame.open("savegame.txt", ios_base::in);

  //Checking if file is open
  if (!MySaveGame) {
    cout << "Error in opening file!" << endl;
    return -1;
  }...


Finally, let’s read the data in the text file and display the user’s gold amount:

...  //reading and printing file content
  while (!MySaveGame.eof()) {
    int moneyAmount;
    MySaveGame >> moneyAmount;
    cout << "Your hero has got " << moneyAmount << " Gold coins!";
  }
  //closing the file
  MySaveGame.close();
  return 0;
}

We get the following output :

Your hero has got 50 Gold coins!

Keep Learning C++ With Udacity

We hope this guide has given you a better understanding of user input, which is an essential aspect of C++ programming. Through our example game, we covered typical situations in which user input is required, as well as how to properly read data from files using C++.

Ready to take your C++ education to the next level?

Udacity offers a highly-acclaimed C++ Nanodegree that turns intermediate C++ coders into fully fledged developers.

Enroll in our C++ Nanodegree program today!

Complete code examples

Program 1 (string and char user input) :

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main() {

  // Let's set up some default and custom options for character names
  string playerName;
  vector<string> options = {"Frodo", "Bilbo", "Gandalf",
    "Aragorn", "Custom name"};
  char playerAnswer;

  // Now, we offer the options to our player
  // (including the Custom option)
  cout << "Welcome, my friend!" << endl;
  cout << "First, tell me more about you... What's your name?" << endl;

  for (int i=0; i<options.size(); ++i) {
    // Convert an index into a letter starting with A, as letter can be
    // easier to input. So index 0 == 'A', 1 == 'B', and so on.
    char opt = 'A' + i;
    cout << opt << " - " << options[i] << endl;
  }

  // Use cin to get the player's input from the console
  cin >> (playerAnswer);

  // Convert any character input into uppercase, and then
  // convert it back into our index format, so 0 == 'A',
  // 1 == 'B', and so on.
  int choiceIndex = toupper(playerAnswer) - 'A';

  if (choiceIndex >= 0 and choiceIndex <  options.size()) {
    // The player specified a valid option
    playerName = options[choiceIndex];
  } else {
    cout << "You haven't picked any of the default options." << endl;
    cout << "Enter your custom name below:" << endl << "> ";
    cin >> playerName;
  }

  cout << "Nice to meet you, " << playerName << "!" << endl;
}

Program 2 (numbers):

#include <iostream>
#include <fstream>
using namespace std;

int main() {
  int playerMoney = 500;
  float riddleAnswer = 85.5;
  float playerRiddleAnswer;

  // Let's present the riddle to the player and ask for their answer
  cout << "Hello, friend. I've got a challenge for you. ";
  cout << "If you succeed, you will get 200 Gold coins. Otherwise, I will keep my money!" << endl;
  cout << "Here is the question: If the distance between the Shire and Mordor is 1197 miles,";
  cout << "how long will it take Frodo to reach it if he travels at 14 miles/day?" << endl;
    
  cout << "> ";
  cin >> playerRiddleAnswer;

  //Check that the player enters the right type
  while (!cin) {
    // Clear the error flag
    cin.clear();
    //Ignore the characters to avoid looping forever
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "Error: Please enter a numeric answer, friend!" << endl;
    cout << "> ";
    cin >> playerRiddleAnswer;
  }

  // Check whether the answer is correct and respond accordingly
  if (playerRiddleAnswer == riddleAnswer) {
    playerMoney = playerMoney + 200;
    cout << "Congratulations, you just earned 200 Gold coins." << endl;
  }
  else {
    cout << "Unfortunately, the correct answer is " << riddleAnswer << "... You'll do better next time!";
  }
  cout << "You have " << playerMoney << " Gold coins in your pocket.";
}


Program 3 (Read from a file):

#include <iostream>
#include <fstream>
using namespace std;

int main() {
  //First, we create a text file and write save game data in it
  ofstream MyFile("savegame.txt");
  MyFile << 50; // initial amount of gold coins
  MyFile.close();

  //Now, we read the data from the text file to store it in a variable
  ifstream MySaveGame;

  //Opening the save game file
  MySaveGame.open("savegame.txt", ios_base::in);

  //Checking if file is open
  if (!MySaveGame) {
    cout << "Error in opening file!" << endl;
    return -1;
  }

  //reading and printing file content
  while (!MySaveGame.eof()) {
    int moneyAmount;
    MySaveGame >> moneyAmount;
    cout << "Your hero has got " << moneyAmount << " Gold coins!";
  }
  //closing the file
  MySaveGame.close();
  return 0;
}