Input & Output (cin & cout)
Programs that talk to people need to read input and print output. In this lesson you'll master for reading, for whole lines, for printing, formatting with , and how to recover gracefully when the user types something unexpected.
Learn Input & Output (cin & cout) in our free C++ course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick recall.
Part of the free C++ course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Think of cin as a conveyor belt carrying everything the user typed, separated by gaps (whitespace). The operator is a robot arm that grabs one item off the belt and stops at the first gap. getline is a bigger scoop that takes the entire row up to the next newline. The catch: when you switch from the small arm to the big scoop, a leftover "end of row" marker is still on the belt — and the scoop grabs that first unless you sweep it off with cin.ignore() .
1. Reading with
The extraction operator reads one whitespace-separated token and converts it to match the variable's type. A word goes into a string , a number into an int or double . You can chain several reads on one line.
2. Reading Whole Lines with getline
Because stops at the first space, it can't read "Ada Lovelace" into one string. reads everything up to the Enter key — spaces and all — which is what you want for names, addresses, and sentences.
3. The then getline Trap
This is the single most common beginner I/O bug. After reads the number, the newline you pressed stays in the buffer. The next getline grabs that empty leftover and returns immediately. The fix is one line: cin.ignore(...) to discard the stray newline before calling getline .
4. Formatting Output with
By default cout prints up to 6 significant digits and trims trailing zeros, which looks wrong for money. Combine std::fixed with std::setprecision(n) for exactly n decimal places, and use std::setw(n) to pad a value into a fixed-width column for neat tables.
5. Handling Bad Input
If the user types letters when you expect a number, cin enters a failed state and stops reading. A robust program checks the result of , calls cin.clear() to reset the error, and cin.ignore(...) to throw away the offending input before trying again.
This program should read an age (number) and then a full name (line). The lines are scrambled — order them so the getline works correctly.
Why: declare the variables first, then read the number with . The crucial step is cin.ignore() between the and the getline — it removes the leftover newline. Without it (line C in the wrong place), getline would read an empty string. Finally print, then return.
Predict the output before revealing each answer.
Grace — stops at the first space, so only the first word is read. The rest ("Hopper") stays on the input buffer.
7.00 — fixed with setprecision(2) forces exactly two decimal places.
cin enters a failed (fail) state ; n is set to 0 and all further extractions fail until you call cin.clear() and cin.ignore(...) .
Read an item, a price, and a quantity, then print a formatted receipt with the total to two decimal places. Match the expected output in the comments.
Practice quiz
If the input is "Grace Hopper" and you do cin >> word; cout << word; what prints?
- Grace Hopper
- Hopper
- Grace
- An empty string
Answer: Grace. The >> operator stops at the first whitespace, so it reads only the first token, 'Grace'. The rest stays on the input buffer.
Which function reads a whole line, including spaces, up to the Enter key?
- getline(cin, line)
- cin >> line
- cin.read(line)
- cin.get(line)
Answer: getline(cin, line). getline(cin, line) reads everything up to (but not including) the newline, so it captures multi-word input like 'Ada Lovelace'.
Why might a getline right after cin >> age return an empty string?
- getline is broken
- age was negative
- You must call cin.flush()
- The leftover newline from the >> read is still in the buffer and getline reads it
Answer: The leftover newline from the >> read is still in the buffer and getline reads it. After cin >> age, the newline you pressed stays in the buffer. The next getline reads that leftover newline. Fix it with cin.ignore() in between.
What does cout << fixed << setprecision(2) << 7.0; print?
- 7
- 7.00
- 7.0
- 7.000
Answer: 7.00. fixed with setprecision(2) forces exactly two decimal places, so 7.0 prints as 7.00.
Without 'fixed', what does setprecision(n) count?
- Total significant digits
- Decimal places
- Field width
- Trailing zeros
Answer: Total significant digits. setprecision alone counts total significant digits. You need std::fixed together with it to get exactly n decimal places.
What is the main difference between endl and ' '?
- endl prints two newlines
- ' ' flushes but endl does not
- endl also flushes the output buffer, which has a small cost
- They are identical in every way
Answer: endl also flushes the output buffer, which has a small cost. Both move to a new line, but endl also flushes the buffer immediately. Prefer ' ' for ordinary output; use endl only when you need a flush.
What does std::setw(8) do?
- Sets 8 decimal places
- Pads the next value to a field 8 characters wide
- Skips 8 characters of input
- Repeats output 8 times
Answer: Pads the next value to a field 8 characters wide. setw(n) pads the next value into a field n characters wide (right-aligned by default). It applies only to the next value.
If the user types letters when cin expects an int, what happens?
- The program crashes
- The int becomes a random value
- cin reads the letters as ASCII codes
- cin enters a failed state and all further reads fail until you clear it
Answer: cin enters a failed state and all further reads fail until you clear it. Extraction fails, cin enters a failed state (the variable is set to 0 since C++11), and further reads fail until cin.clear() and cin.ignore().
Which two calls recover a failed cin so you can re-prompt?
- cin.reset() and cin.flush()
- cin.clear() and cin.ignore(...)
- cin.good() and cin.eof()
- cin.open() and cin.close()
Answer: cin.clear() and cin.ignore(...). cin.clear() resets the error state, then cin.ignore(...) discards the bad input still sitting in the buffer before you try again.
Which header do you include for setprecision, fixed, and setw?
- <iostream>
- <string>
- <iomanip>
- <cstdio>
Answer: <iomanip>. The formatting manipulators setprecision, fixed, setw, left, and right live in <iomanip>.