Lesson 17 +10 XP

New Lines

You've got text, now let's decide where lines break. Two tools: the escape and the manipulator endl.

The escape:

Inside a string, `

` means "start a new line here":


cpp
cout << "Hello
world";

Output:


### Hello
world

Same trick, separate pieces

You can also make it a separate fragment:


cpp
cout << "Hello" << "
" << "world";

Same two lines.

The manipulator: endl

endl does the same job, written after <<:


cpp
cout << "Hello" << endl;
cout << "world";

Output: still two lines. Notice there's no quote around endl - it's not text, it's a stream helper.

Multiple newlines

Each `

` jumps one line, so two of them create a blank line:


cpp
cout << "a

b";

Output: an empty line sits between a and b.

vs endl

  • `

` only adds a newline character.

  • endl adds a newline and flushes the output buffer.
  • Flushing can slow big programs down, so for plain text `

` is usually the smarter pick.

TL;DR

  • `

` inside a string starts a new line.

  • endl also starts a new line, and it flushes too.
  • `

` produces a blank line.

  • Prefer `

for most plain text; keep endl` for when you want an immediate flush.