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:
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:
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:
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:
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: