1.6 — Reading input with std::cin
Read one box at a time. No rush.
Asking the user#
std::cin means "character input". It reads what the user types.
Use >> — the arrows point into the variable.
C++▶ Run
#include <iostream> int main(){ std::cout << "How old are you? "; int age {}; std::cin >> age; std::cout << "Next year you will be " << age + 1 << "!\n"; return 0;}Output
How old are you? 12Next year you will be 13!Reading several values#
C++
int a {};int b {};std::cout << "Enter two numbers: ";std::cin >> a >> b;std::cout << "Sum: " << a + b << '\n';The user can type 3 4 and press Enter.
Easy way to remember#
std::cout << x— data goes out to the screen.std::cin >> x— data comes in tox.
Watch out
std::cin >> name with a std::string only reads one word. "Sam Smith" becomes just "Sam". To read a whole line, see 8.5 — String tools.
Tip
If the user types letters when you asked for a number, std::cin fails and the variable becomes 0. We will learn to handle that later. For now, type numbers when asked for numbers!
Tip: press ← / → to move between lessons, / to search.