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++ devloper 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 Next, we’ll want the player to either create a name for the character or choose from one of the predefined options
- 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.
#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;...
..
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 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.
- 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.
- 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.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
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;...
.." //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;
}...
...//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