std::cin &
Whitespace
Master how C++ reads input from the keyboard: how std::cin handles spaces, tabs, and newlines, and why it matters for your programs.
What is std::cin?
std::cin is the standard input stream object in C++. It reads data that users type on the keyboard and stores it into variables using the extraction operator >>.
The Input Buffer
When you type on the keyboard, characters go into an input buffer (a waiting area). When you press Enter, the buffer becomes available to your program.
What Counts as Whitespace?
In C++, whitespace refers to invisible characters that create spacing. The extraction operator >> treats all of them the same way: it skips leading whitespace and stops at the next whitespace.
How >> Actually Works
The extraction operator follows a two-step process every time it reads:
The Core Rule
>> vs std::getline
| std::cin >> | std::getline() | |
|---|---|---|
| Reads | One token (word) | Entire line |
| Delimiter | Any whitespace | Newline '\n' only |
| Leading spaces | Skipped | Preserved |
| Delimiter consumed? | No (stays in buffer) | Yes (discarded) |
| Use case | Single words, numbers | Full names, sentences |
Chaining Multiple Reads
You can chain >> to read multiple values. Each extraction skips whitespace, reads a token, and leaves the rest for the next.
Step-by-Step Approach
Before writing any input code, follow this checklist to avoid whitespace bugs:
Example 1: Reading a Single Word
Example 2: The Whitespace Trap
Example 3: The Fix with getline
The Mixing Problem
The most common bug: using >> followed by getline. The leftover newline from >> gets consumed by getline instantly.
The Fix: cin.ignore()
Common Mistakes
Summary Reference Table
| Scenario | Tool | Example |
|---|---|---|
| Read one integer | cin >> n | "42" → 42 |
| Read one word | cin >> word | "Hello" → "Hello" |
| Read full line | getline(cin, str) | "Hello World" → "Hello World" |
| Number then line | cin >> n; cin.ignore(); getline(...); | Must ignore '\n' |
| Two numbers | cin >> a >> b | "3 7" → a=3, b=7 |
Question 1 of 5
What does std::cin >> do when it encounters leading spaces in the input buffer?
Question 2 of 5
Consider this code:
std::string word;
std::cin >> word;
std::cout << word;
The user types: "Hello World" and presses Enter.
What is printed to the screen?
Question 3 of 5
You use cin >> age to read an integer, then immediately use getline(cin, city). The getline reads an empty string. What is the cause?
Question 4 of 5
Which function should you use to read an entire line of text that may contain spaces?
Question 5 of 5
Consider this code:
int x, y;
std::cin >> x >> y;
std::cout << x + y;
The user types: " 10 20" (with extra spaces) and presses Enter.
What is the output?