C++ ยท Chapter 5 of 49

C++ Output

The `std::cout` object, combined with the `<<` insertion operator, is the standard way to print to the console in C++. You can chain multiple `<<` operators to print several values in one statement.

Use `std::endl` or `\n` to move to a new line. `std::endl` also flushes the output buffer, while `\n` is slightly faster.

Printing values

`cout << "text"` prints a string literal; you can also print numbers, characters, and variables directly, all chained with `<<`.

New lines

`\n` inside a string literal inserts a newline character. `std::endl` does the same but also forces the buffer to flush to the terminal immediately.

Example 1 (cpp)
#include <iostream>
using namespace std;
int main() {
    cout << "Score: " << 95 << "\n";
}
Output
Score: 95

Chaining << lets you mix strings and numbers in one line.

Example 2 (cpp)
cout << "Line1" << endl << "Line2";
Output
Line1
Line2

endl moves to the next line and flushes output.

Key points

  • std::cout with << prints to the console.
  • You can chain multiple << in one statement.
  • \n inserts a newline; endl also flushes the buffer.
  • using namespace std lets you drop the std:: prefix.
๐Ÿ’ก Note: Prefer \n over endl in performance-critical loops, since endl's flush is comparatively slow.

๐Ÿ“ Quick Quiz

1. What operator is used with cout?

2. Which prints a newline AND flushes the buffer?

3. Which header is required for cout?