C++ Escape Sequences
Escape sequences are special characters in C++ used to represent characters that are difficult to type or have special meaning. They are prefixed with a backslash \ inside string literals.
1. Common Escape Sequences
| Escape Sequence | Meaning | Example Output |
|---|---|---|
| \n | Newline | Moves text to the next line |
| \t | Horizontal tab | Adds a tab space |
| \\ | Backslash | Prints a backslash \ |
| \" | Double quote | Prints a double quote " |
| \' | Single quote | Prints a single quote ' |
| \r | Carriage return | Moves cursor to start of line |
| \b | Backspace | Deletes previous character |
| \a | Alert/Bell | Triggers a beep sound |
| \0 | Null character | String terminator |
2. Examples of Escape Sequences
C++
Using escape sequences in output
#include <iostream>
using namespace std;
int main() {
cout << "Hello\nWorld!" << endl; // Newline
cout << "Column1\tColumn2" << endl; // Tab
cout << "Path to file: C:\\Program Files\\CodeCrown" << endl; // Backslash
cout << "Quote: \"CodeCrown\"" << endl; // Double quote
return 0;
}
3. Interactive Example
C++
Demonstration program with multiple escape sequences
#include <iostream>\nusing namespace std;\n\nint main() {\n cout << "List of items:\\n";\n cout << "1. Apples\\n";\n cout << "2. Oranges\\n";\n cout << "3. Bananas\\n";\n cout << "Price per item:\\t$1.50" << endl;\n cout << "Special characters: \\\\ \\" \\'" << endl;\n return 0;\n}
Conclusion
Escape sequences in C++ provide a way to include special characters in strings and output. Using them effectively allows formatted output, proper string handling, and readable code.
Codecrown