Escape sequences – special characters

Escape sequences are special sequences of characters used within string and character literals to represent characters that are difficult or impossible to type directly. Escape sequences begin with a backslash (\) followed by one or more characters. They are mainly used to represent control characters (like newline or tab) or to insert characters that are not directly typable (like double quotes inside a string).

Common Escape Sequences in C++

Here are some of the most commonly used escape sequences in C++:

Escape SequenceMeaning
\\Backslash
\'Single quote
\"Double quote
\?Question mark
\aAudible alert (bell)
\bBackspace
\fForm feed (page break)
\nNewline (line feed)
\rCarriage return
\tHorizontal tab
\vVertical tab
\0Null character
\xhhHexadecimal number (hh represents hexadecimal digits)
\nnnOctal number (nnn represents octal digits)
\uhhhhUnicode character (16-bit)
\UhhhhhhhhUnicode character (32-bit)

Example 1: Using Escape Sequences for Special Characters

#include <iostream>
using namespace std;

int main() {
    // Example 1: Using escape sequences for special characters
    string message = "Hello,\n\tC++!\nI hope you're enjoying programming.\n\nThis is a backslash: \\\nAnd this is a double quote: \"";

    cout << message << endl;
    
    return 0;
}

Explanation:

  • \n is used for a newline character. It moves the cursor to the next line.
  • \t is used for a tab character. It adds a tab space.
  • \\ is used to insert a literal backslash \. In C++ strings, a single backslash \ is used to escape special characters, so \\ is necessary to display a single backslash.
  • \" is used to insert a double quote character " within a string that is already enclosed in double quotes. This escapes the character to prevent the string from being prematurely terminated.
  • cout << message << endl; prints the contents of the message string followed by a newline (endl).

Output:

When you run the code, the output will be:

Hello,
    C++!
I hope you're enjoying programming.

This is a backslash: \
And this is a double quote: "

Example 2: Using Unicode Escape Sequence

#include <iostream>
using namespace std;

int main() {
    // Example 2: Using Unicode escape sequence
    string unicodeString = "\u0048\u0065\u006C\u006C\u006F, \u4E16\u754C!";

    cout << unicodeString << endl;
    
    return 0;
}

Explanation:

  • \uXXXX is the Unicode escape sequence where XXXX represents the hexadecimal code of the Unicode character.
  • In this example, \u0048 corresponds to the Unicode character ‘H’, \u0065 corresponds to ‘e’, \u006C corresponds to ‘l’, \u006F corresponds to ‘o’, \u4E16 corresponds to the Chinese character ‘世’, and \u754C corresponds to ‘界’.
  • cout << unicodeString << endl; prints the contents of unicodeString followed by a newline (endl).

Output:

When you run the code, it prints:

Hello, 世界!