1.2 — Printing with std::cout

📘 Chapter 1⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Showing text#

std::cout means "character output". It shows things on the screen.

Use << to send things to it. Think of << as an arrow pointing to the screen.

C++
std::cout << "Hello!";

Printing numbers#

Numbers do not need quotes.

C++
std::cout << 42;
Output
42

Chaining#

You can send many things in one line with more <<.

C++
std::cout << "Score: " << 100 << " points";
Output
Score: 100 points

New lines#

Text does not move to a new line by itself. Use \n (inside quotes) to start a new line.

C++
std::cout << "Line one\n";std::cout << "Line two\n";
Output
Line oneLine two

You may also see std::endl. It also ends the line:

C++
std::cout << "Hello" << std::endl;
Good habit

Prefer '\n' or "\n" over std::endl. std::endl also forces the text out right away, which makes printing slower. You almost never need that.

Tired of typing std::?#

std:: means "from the standard library" — the toolbox that comes with C++.

You might see using namespace std; at the top of some code. Then you can write cout instead of std::cout.

Watch out

This guide always writes std::. In big programs, using namespace std; can cause name clashes. Writing std:: is clearer and safer.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.