Lesson 17 +10 XP

New Lines

New Lines

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

The escape: \n

Inside a string, \n means "start a new line here":

cout << "Hello\nworld";

Output:

Hello
world

Same trick, separate pieces

You can also make it a separate fragment:

cout << "Hello" << "\n" << "world";

Same two lines.

The manipulator: endl

endl does the same job, written after <<:

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 \n jumps one line, so two of them create a blank line:

cout << "a\n\nb";

Output: an empty line sits between a and b.

\n vs endl

  • \n only adds a newline character.
  • endl adds a newline and flushes the output buffer.
  • Flushing can slow big programs down, so for plain text \n is usually the smarter pick.

TL;DR

  • \n inside a string starts a new line.
  • endl also starts a new line, and it flushes too.
  • \n\n produces a blank line.
  • Prefer \n for most plain text; keep endl for when you want an immediate flush.