1.2 — Printing with std::cout
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.
std::cout << "Hello!";Printing numbers#
Numbers do not need quotes.
std::cout << 42;42Chaining#
You can send many things in one line with more <<.
std::cout << "Score: " << 100 << " points";Score: 100 pointsNew lines#
Text does not move to a new line by itself. Use \n (inside quotes) to start a new line.
std::cout << "Line one\n";std::cout << "Line two\n";Line oneLine twoYou may also see std::endl. It also ends the line:
std::cout << "Hello" << std::endl;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.
This guide always writes std::. In big programs, using namespace std; can cause name clashes. Writing std:: is clearer and safer.
Tip: press ← / → to move between lessons, / to search.