Loading lessons...
Escape Sequences in Strings
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.\nprints a newline.\tprints a tab.\0is the null character (used by C-style strings).
In action
cout << "She said \"hi\"." << endl;
// She said "hi".
cout << "line one\nline 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
| Escape | Meaning |
|---|---|
\\ | Backslash |
\" | Double quote |
\n | New line |
\t | Tab |
\0 | Null character |
TL;DR
- Escapes start with a backslash.
\"puts a quote inside a string.\nand\tformat output.\\writes one backslash.\0is the null character.