Escape Sequence

Estimated reading: 2 minutes 944 Views

Escape sequences are special characters that are used to represent non-printing characters or to control the behavior of output streams. They are prefixed with a backslash (\).

Types of Escape Sequences

There are three types of escape sequences in C++:

  • Character escape sequences: These escape sequences represent non-printing characters, such as newline, tab, and backspace.
  • Hexadecimal escape sequences: These escape sequences represent characters using their hexadecimal values.
  • Octal escape sequences: These escape sequences represent characters using their octal values.

Common Escape Sequences

Here are some of the most common escape sequences in C++:

Escape Sequence Description
\n Newline
\t Tab
\\ Backslash
\" Double quote
\' Single quote
\? Question mark
\a Alert
\b Backspace
\f Form feed
\r Carriage return
\v Vertical tab
\x Hexadecimal escape sequence
\NNN Octal escape sequence

Using Escape Sequences

Escape sequences can be used in string and character literals. For example, the following code prints the string “Hello, world!” followed by a newline character:

C++
std::cout << "Hello, world!" << std::endl;

The std::endl object represents the newline character. It is equivalent to the escape sequence \n.

Escape sequences can also be used to represent non-printing characters, such as the tab character. For example, the following code prints the string “Hello, world!” followed by a tab character:

C++
std::cout << "Hello, world!" << '\t';

Example

Here are some more examples of how to use escape sequences in C++:

C++
// Print the string "This is a quote \" inside a string." 
std::cout << "This is a quote \" inside a string."; 

// Print the character 'a' with a backspace before it. 
std::cout << '\b' << 'a';

// Print the string "Hello, world!" followed by a newline character and a tab character. 
std::cout << "Hello, world!" << std::endl << '\t';
Conclusion

Escape sequences are a powerful tool that can be used to control the behavior of output streams and to represent non-printing characters in C++.

Share this

Escape Sequence

Or copy link

CONTENTS
English