Formatted Output
with std::cout
Learn how to display text and data to the console using the C++ insertion operator, escape sequences, and stream manipulators.
What is std::cout?
std::cout stands for Character Output. It is a predefined object in C++ that represents the standard output stream, typically your terminal or console window. It lives inside the <iostream> header and the std namespace.
The Insertion Operator <<
The << operator inserts data into the output stream. You can chain multiple << operators to send several items in one statement. Data flows left to right.
Why Formatting Matters
The Basic Pattern
Escape Sequences
Escape sequences are special character combinations starting with a backslash \. They let you insert characters that cannot be typed directly into a string literal.
| Sequence | Meaning | Example Output |
|---|---|---|
| \n | New line | Line 1 Line 2 |
| \t | Horizontal tab | Col1 Col2 |
| \\ | Backslash | C:\path |
| \" | Double quote | She said "hi" |
std::endl vs \n
Stream Manipulators
The <iomanip> header provides manipulators that control how data is formatted. They are inserted into the stream like regular data and change the formatting for all subsequent output.
How to Format Output
Example 1: Mixing Text and Variables
Example 2: Decimal Precision
Example 3: Field Width and Alignment
Chaining Multiple Items
Manipulator Persistence
Common Mistakes
Manipulator Summary
| Manipulator | Header | Persistence | Purpose |
|---|---|---|---|
| std::endl | <iostream> | One-shot | Newline + flush |
| std::setw(n) | <iomanip> | One-shot | Field width |
| std::setprecision(n) | <iomanip> | Sticky | Decimal digits |
| std::fixed | <iomanip> | Sticky | Decimal notation |
| std::left / std::right | <iomanip> | Sticky | Alignment |
| std::setfill(c) | <iomanip> | Sticky | Fill character |
Question 1 of 5
What does the << operator do in the context of std::cout?
Question 2 of 5
What will the following code output?
Question 3 of 5
Which header must you include to use std::setprecision?
Question 4 of 5
What happens if you call std::setw(10) once and then output three values without calling setw again?
Question 5 of 5
What will this code output?