Lesson 52 +10 XP

Escape Sequences in Strings

Some characters are impossible to type as-is inside a string. Escape sequences solve that: a backslash \ followed by a letter or symbol.

The classic escapes

  • \\ prints a backslash.
  • \" prints a double quote.
  • `

` prints a newline.

  • \t prints a tab.
  • \0 is the null character (used by C-style strings).

In action


cpp
cout << "She said \"hi\"." << endl;
// She said "hi".

cout << "line one
line two" << endl;
// line one
// line two

cout << "col1\tcol2" << endl;
// col1    col2

Why the backslash?

A string is bounded by double quotes. To place a real quote inside, you tell the compiler "this quote is text, not the end of the string" - that is what \" does. And because the backslash itself starts escapes, a real backslash is written as \\.

Escape table

EscapeMeaning
\\Backslash
\"Double quote

` | New line |

TL;DR

  • Escapes start with a backslash.
  • \" puts a quote inside a string.
  • `

and \t` format output.

  • \\ writes one backslash.
  • \0 is the null character.