Learn C++ · lesson 5 of 61 · about 8 minutes
Reading Input with cin
Let the player play: read their name with getline and the path they choose with std::cin >>.
What you'll learn
- Read values with std::cin >>
- Read several values at once
- Read a whole line with std::getline
Let the player play
So far your adventure plays itself. A game needs a player: someone who types a name and picks a path.
std::cin >> path; reads what the player types into a variable. The arrows point the way the data flows: out of cin, into the variable.
Pick a path
#include <iostream>
#include <string>
int main() {
std::string path;
std::cout << "Which way? ";
std::cin >> path;
std::cout << "You head " << path << ".\n";
}Output
Which way? You head north.Words and whole lines
>> reads one word at a time, stopping at the first space. It reads numbers too: if the player types 3 and the variable is an int, it gets the number 3.
A name like Ada the Brave has spaces in it, so read the whole line instead: std::getline(std::cin, hero);.
A line, then a number
#include <iostream>
#include <string>
int main() {
std::string hero;
int potions;
std::getline(std::cin, hero);
std::cin >> potions;
std::cout << hero << " has " << potions + 2 << " potions\n";
}Output
Ada the Brave has 5 potionsTip
Mixing >> and getline can surprise you: >> leaves the end of the line behind, so a getline straight after it reads an empty line. Read lines first, or skip the leftover with std::cin >> std::ws before the getline.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.