C++ Escape Sequences

Escape sequences are used to represent certain characters within a string, which would otherwise not be possible to include. In C++, escape sequences start with a back slash (\), which is then followed by one or more characters.

As previously discussed, a message can be written out to the console using a ‘cout’ statement.

cout << "This is a string." << endl;

This writes out the message, ‘This is a string’, to the console. As can be seen in the above code, the message is contained in double quotes. In order to get a double quote to actually appear in the message within the console, an escape sequence needs to be used.

cout << "This is a string containing \"double quotes\"." << endl;

Here, a back slash is placed before the double quote in order to get it to appear in the message.

This is a string containing "double quotes".

As well as using an escape sequence for printable characters, such as double quotes, they can also be used for non-printable characters, such as including a new line within a string.

cout << "This is a string containing\na new line." << endl;

The escape sequence ‘\n’ is used within this message to force part of it to appear on a new line.

This is a string containing
a new line.

Below is a table containing some of the escape sequences that are available in C++.

\a Bell (alert)
\b Backspace
\f Formfeed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\’ Single quotation mark
\” Double quotation mark
\\ Back slash
\? Literal question mark