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).
Here are some of the most commonly used escape sequences in C++:
| Escape Sequence | Meaning |
|---|---|
\\ | Backslash |
\' | Single quote |
\" | Double quote |
\? | Question mark |
\a | Audible alert (bell) |
\b | Backspace |
\f | Form feed (page break) |
\n | Newline (line feed) |
\r | Carriage return |
\t | Horizontal tab |
\v | Vertical tab |
\0 | Null character |
\xhh | Hexadecimal number (hh represents hexadecimal digits) |
\nnn | Octal number (nnn represents octal digits) |
\uhhhh | Unicode character (16-bit) |
\Uhhhhhhhh | Unicode character (32-bit) |
#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: "
#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.\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, 世界!