Notes – Escape Sequence in C++
An escape sequence in C++ is a special character combination starting with a backslash \, used to represent characters that are difficult or impossible to type directly into a string.
Escape sequences are mostly used in cout statements, character constants, and string literals.
Why Use Escape Sequences?
- To format output
- To insert special characters like newlines, tabs, quotes, or backslashes
- To control spacing and behavior of console output
Commonly Used Escape Sequences
| Escape Sequence | Meaning | Example | Output Description |
|---|---|---|---|
\n | New line | cout << "Hello\nWorld"; | Moves to the next line |
\t | Horizontal tab | cout << "Name\tAge"; | Inserts a tab space |
\\ | Backslash | cout << "C:\\Files"; | Prints a single backslash |
\" | Double quote | cout << "He said \"Hi\""; | Prints quotes inside string |
\' | Single quote | cout << "It\'s fine"; | Prints single quote |
\a | Alert (beep) | cout << "\a"; | Triggers system alert (if enabled) |
\b | Backspace | cout << "Helloo\b"; | Removes previous character |
\r | Carriage return | Platform dependent | Moves cursor to beginning of line |
\0 | Null character (string terminator) | Used internally in strings | Marks end of a C-style string |
Example Program
#include <iostream>
using namespace std;
int main() {
cout << "Welcome\tto\nC++ Programming!\n";
cout << "Path: C:\\Program Files\\App\n";
cout << "Quote: \"Learn C++\"\n";
return 0;
}
Notes
- Escape sequences are used within double quotes (” “)
\nand\tare the most commonly used- Avoid using
\aor\runless necessaryโthey are platform-dependent
Use Cases
- Formatting console output
- Inserting quotes, tabs, and line breaks into strings
- Handling file paths and special characters in user messages
