← Back to C++ Course | Chapter 2: Input & Output | Lesson 6 of 8

C++ Escape Sequences

Newline Escape Sequence

\n inserts a newline directly inside a string literal, letting you break output across multiple lines without needing several separate cout statements. It's the most commonly used escape sequence in C++, showing up in nearly every program that prints more than a single line.

Example: Newline Escape Sequence

cpp
#include <iostream>

int main() {
	std::cout << "Line one\nLine two\n";
	return 0;
}

Tab Escape Sequence

\t inserts a horizontal tab, which is commonly used to line up columns of output — for example, aligning a list of names against a list of scores so they read like a table. The exact width of a tab can vary between terminals, so for precise alignment setw from <iomanip> is often a more reliable choice.

Example: Tab Escape Sequence

cpp
#include <iostream>

int main() {
	std::cout << "Name\tScore\n";
	std::cout << "Amit\t95\n";
	return 0;
}

Quotes and Backslashes

Characters like ", ', and \ carry special meaning in C++ string and character literals, so printing them literally requires escaping them with a preceding backslash — \" for a quote inside a double-quoted string, or \\ for a literal backslash. Without the escape, the compiler would misinterpret the character as ending the string early.

Example: Quotes and Backslashes

cpp
#include <iostream>

int main() {
	std::cout << "She said \"hello\"" << std::endl;
	std::cout << "Path: C:\\Users" << std::endl;
	return 0;
}

Carriage Return

\r, carriage return, moves the cursor back to the start of the current line without advancing to a new one, which lets a following print overwrite what's already there. This is the trick behind simple in-place progress indicators in terminal programs, like a percentage counter that updates on the same line instead of scrolling.

Example: Carriage Return

cpp
#include <iostream>

int main() {
	std::cout << "Loading...\r";
	std::cout << "Done!      " << std::endl;
	return 0;
}

Alarm or Bell Sound

\a triggers the terminal's alert sound or visual bell when printed, a holdover from early terminal hardware that had a literal physical bell. It's rarely used in modern applications, but can still serve as a simple audible notification in command-line tools running in a terminal that supports it.

Example: Alarm or Bell Sound

cpp
#include <iostream>

int main() {
	std::cout << "Alert\a" << std::endl;
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.