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 SequenceMeaningExampleOutput Description
\nNew linecout << "Hello\nWorld";Moves to the next line
\tHorizontal tabcout << "Name\tAge";Inserts a tab space
\\Backslashcout << "C:\\Files";Prints a single backslash
\"Double quotecout << "He said \"Hi\"";Prints quotes inside string
\'Single quotecout << "It\'s fine";Prints single quote
\aAlert (beep)cout << "\a";Triggers system alert (if enabled)
\bBackspacecout << "Helloo\b";Removes previous character
\rCarriage returnPlatform dependentMoves cursor to beginning of line
\0Null character (string terminator)Used internally in stringsMarks 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 (” “)
  • \n and \t are the most commonly used
  • Avoid using \a or \r unless 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