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 SequenceMeaningExample Output
\nNewlineMoves text to the next line
\tHorizontal tabAdds a tab space
\\BackslashPrints a backslash \
\"Double quotePrints a double quote "
\'Single quotePrints a single quote '
\rCarriage returnMoves cursor to start of line
\bBackspaceDeletes previous character
\aAlert/BellTriggers a beep sound
\0Null characterString 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.