← C++ from Scratch Lesson 7 of 62 · 10 XP

Input: std::cin

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

std::cin >> x reads a value from the console and puts it into x, skipping spaces and line breaks:

int a, b;
std::cin >> a >> b;          // the input "3 4" or "3\n4"
std::cout << a + b << '\n';  // 7

std::string word;
std::cin >> word;            // reads one word — up to a space

std::string line;
std::getline(std::cin, line);   // reads the whole line, spaces included

A trap: after std::cin >> n, a \n stays in the buffer, and the next getline reads an empty line. The cure is std::cin >> std::ws; before getline — it skips whitespace characters.

Task. Read a name (one word) and a year of birth, and print Hello, <name>! You turn <age> in 2026.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.