Loading lessons...
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
\nonly adds a newline character.endladds a newline and flushes the output buffer.- Flushing can slow big programs down, so for plain text
\nis usually the smarter pick.
TL;DR
\ninside a string starts a new line.endlalso starts a new line, and it flushes too.\n\nproduces a blank line.- Prefer
\nfor most plain text; keependlfor when you want an immediate flush.