Learn C++ escape sequences with practical examples. Understand newline, tab, quote, backslash, and other special characters used in output strings and beginner C++ programs.
Escape sequences are special characters used inside a C++ string to perform a specific action or display special characters.
An escape sequence usually starts with a backslash (\).
| Escape Sequence | Name | Purpose |
|---|---|---|
\n |
Newline | Moves the cursor to the next line |
\t |
Tab | Adds a horizontal tab space |
\\ |
Backslash | Displays a backslash \ |
\" |
Double Quote | Displays a double quotation mark " |
\' |
Single Quote | Displays a single quotation mark ' |
\r |
Carriage Return | Moves the cursor to the beginning of the current line |
\n\n?The \n escape sequence is used to move the cursor to the next line.
It is similar to using endl.
Write a C++ program that prints two lines of text using the newline escape sequence \n.
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!\n";
cout << "Welcome to C++.";
return 0;
}
Hello World!
Welcome to C++.
cout << "Hello World!\n";
The \n moves the cursor to the next line. Therefore, the second cout statement starts on a new line.
\n → New line
\t\t?The \t escape sequence inserts a horizontal tab space.
It is useful for creating simple columns in output.
Write a C++ program that displays a list of items and their prices using \t to separate the columns.
#include <iostream>
using namespace std;
int main() {
cout << "Item\tPrice\n";
cout << "Apple\t100\n";
cout << "Mango\t150\n";
return 0;
}
Item Price
Apple 100
Mango 150
cout << "Apple\t100\n";
\t adds a tab space between Apple and 100.\n moves the cursor to the next line.\t → Tab space
\\\\?The backslash character \ has a special meaning in C++.
If we want to display an actual backslash, we use two backslashes:
\\
Write a C++ program that displays a Windows file path containing backslashes.
#include <iostream>
using namespace std;
int main() {
cout << "File path: C:\\Users\\Student\\Documents";
return 0;
}
File path: C:\Users\Student\Documents
In the program:
C:\\Users\\Student\\Documents
Each \\ represents one actual backslash in the output.
\\ → Displays \
\"\"?A double quotation mark " normally marks the beginning or end of a string.
If we want to display a double quotation mark inside a string, we use:
\"
Write a C++ program that prints a sentence containing double quotation marks.
#include <iostream>
using namespace std;
int main() {
cout << "He said, \"C++ is fun!\"";
return 0;
}
He said, "C++ is fun!"
\"C++ is fun!\"
The \" tells C++ to display a quotation mark instead of treating it as the end of the string.
\" → Displays "
\'\'?The \' escape sequence can be used to display a single quotation mark.
Write a C++ program that prints a character enclosed in single quotation marks.
#include <iostream>
using namespac