Skip to main content

Section 9.7 Other Escape Sequences

We have already learned that printing \t prints a tab character instead of literally printing a \ and a t. \t is known as an escape sequence. An escape sequence is a sequence of characters used to represent a single character that otherwise might be hard to type or might cause issues with parsing the code. In C++ escape sequences start with a backslash \. Anytime you see that symbol in a char or string, it means β€œstart an escape sequence”. The character that comes after determines what sequence it is:
Table 9.7.1. Common escape sequences
\t tab
\n newline
\" double quote
\' single quote
\\ backslash
An escape sequence represents a single character, and only counts as such despite looking like multiple characters. So the string "a\tb" has a size() of only 3 because \t is one character. The characters in that string look like:
0 1 2
a (tab) b
Other than the tab sequence, the other text important formatting symbol is the \n or newline symbol. When a computer stores a text file, it needs a way to know where each line ends. To do that, the ASCII code 10 is used. It is referred to as the newline character and can be β€œtyped” into a string in C++ using \n. When you print a newline character, the cursor moves to the beginning of the next line. Using this, it is possible to have a single string that represents multiple lines of output. You just have to tell C++ where to put the line breaks:
Listing 9.7.2.
When the string is printed, we do not see the \ns, but they do create new lines.

Note 9.7.1. endl vs \n.

endl and \n both allow us to print newlines. \n can be β€œbuilt into” a string as a character while endl is a special message that is sent to cout. Generally it is preferred to use \n when you are trying to make the newline be part of the string (because you are doing something like building up a multiline file). If you just want to print a newline after a string, it is preferred to use endl instead of modifying the string to include \n.
The other escape symbols are workarounds for the fact that ", ', and \ are special symbols in strings and chars. A " normally marks the start or end of a string. So trying to write this causes errors for the compiler:
cout << "She said "Hello!" to me.";
To the compiler that looks like the string "She said " followed by a variable Hello, the symbol !, and then the string `" to me.".
To include the quotes in the string, we need to escape them using \:
Listing 9.7.3.
The same trick is true of single quotes and of backslashes. Since \ normally means β€œthis is the start of an escape sequence”, we need an escape sequence to indicate that the value we want is really just a backslash. We need to use this trick to represent a Windows style file path that uses backslashes:
Listing 9.7.4.

Checkpoint 9.7.1.

You have attempted of activities on this page.