Console Input and Output

Newlines, Tabs, and Escape Sequences

Consider a situation when there is a need to print a sentence with quotation marks in the output, such as:

The guide said, "Keep left at the fork."

Direct writing of quotation marks in a text string causes certain difficulties since the compiler identifies them as markers of the start and the end of the string.

#include <iostream>

int main()
{
    std::cout << "The guide said, "Keep left at the fork."";
    return 0;
}

The compiler scans a statement from left to right, treating the first quotation mark before The as the start of the string. On seeing the quotation mark before Keep, it treats it as the end of the string and interprets the words that follow as C++ instructions. The fact that these words cannot serve as valid instructions in this context leads to a compilation failure.

In order to overcome this problem, C++ uses escape sequences. Escape sequences begin with a backslash (\), which signals to the compiler that the next character should be treated differently. Instead of displaying the backslash itself, the compiler combines it with the following character to represent a symbol that may otherwise be difficult to write directly.

For example, an escaped quotation mark is treated as part of the text rather than as a marker of the end of the string:

#include <iostream>

int main()
{
    std::cout << "The guide said, \"Keep left at the fork.\"\n";
    return 0;
}

The escape sequence \" tells the compiler to treat the double quotation mark as a literal character that should be displayed.

Escape sequences are processed during the translation of the source code. Although an escape sequence may consist of two characters written in the source file, it usually denotes one character in the resulting text. For example, the two source characters \ and n in "\n" produce one newline character.

It is also possible to display the written form of an escape sequence by escaping its introductory character. Writing "\\n" produces a backslash followed by the letter n, rather than a newline.

Newlines and Tabs

The newline character \n is another example of an escape sequence. It moves subsequent text to the beginning of the next line. C++ offers several other escape sequences that can be used to format console output.

One of the most widely used formatting characters is the horizontal tab, represented by \t. A tab moves the output cursor to the next tab stop and can help organize short pieces of text into columns without manually placing many spaces.

For instance, a program may display a list containing items and their prices:

#include <iostream>

int main()
{
    std::cout << "Item\tPrice\n";
    std::cout << "Apple\t0.99\n";
    std::cout << "Banana\t1.25\n";
    std::cout << "Watermelon\t4.50\n";
    return 0;
}

A tab placed between each item and its price moves the price to the next tab stop.

However, a tab does not insert a constant number of spaces. It moves the cursor to the next tab stop, so the distance depends on the current cursor position. Text that appears aligned in one console may not be aligned in another, especially when earlier fields contain text of different lengths. For tables that require predictable alignment, fixed-width formatting is preferable.

Displaying Backslashes and Single Quotes

As mentioned above, a backslash serves as the introductory character of an escape sequence. Therefore, the backslash itself requires escaping when it needs to be displayed. This is especially important when printing Windows file paths, such as:

C:\temp\new_folder

If the path is written directly inside a string, it may contain combinations that the compiler recognizes as escape sequences:

#include <iostream>

int main()
{
    std::cout << "C:\temp\new_folder\n";
    return 0;
}

In this example, \t is interpreted as a tab and \n is interpreted as a newline. Instead of displaying the intended path, the program prints C:, followed by a tab, then emp, a newline, and finally ew_folder.

To display a literal backslash, another backslash is placed before it. The first backslash informs the compiler that the following backslash should be treated as an ordinary character:

#include <iostream>

int main()
{
    std::cout << "C:\\temp\\new_folder\n";
    return 0;
}

This correctly displays:

C:\temp\new_folder

A similar approach should be taken with a single quotation mark when it is used as a character delimiter. A single quotation mark can normally appear inside a double-quoted string without any additional treatment:

std::cout << "It's fine";

However, when a single quotation mark is represented as an individual character, it must be escaped so that the compiler does not mistake it for the end of the character literal:

char quote{'\''};

Invalid escape sequences, such as \m or \q, should be avoided. Compilers may react to them differently. Some may generate a warning, others may produce an error, and some may interpret the sequence in an implementation-specific way. To avoid unexpected behavior, each backslash in a string or character literal should form a valid escape sequence.

Exercise: Newlines, Tabs, and Escape SequencesStarter code, hints and solutionOpenClose
Guided practiceBeginner · 10–15 min

Practice: Newlines, Tabs, and Escape Sequences

Work through the mission, reveal hints only when needed, and compare your result with the model solution.

Your challenge

Replace Apple with Pear in the table and retain the tab and newline escapes. Explain why the visible column alignment depends on tab stops.

Mission checklist

  1. Run the starter as a baseline, then predict the change requested in Your challenge.
  2. Make that change in your editor; use the lesson-specific hints if you need help.
  3. Compile and run your answer, then compare with the worked solution and explain the result.

Starter program

This is the working baseline, not the completed answer. Compile as C++20, then make the change described above.

#include <iostream>

int main()
{
    std::cout << "Item\tPrice\n";
    std::cout << "Apple\t0.99\n";
    std::cout << "Banana\t1.25\n";
    std::cout << "Watermelon\t4.50\n";
    return 0;
}

Hints

Hint 1

In each string, \t moves to a tab stop and \n starts a new line. The backslash sequences are not printed as two ordinary characters.

Hint 2

Compare the lengths of "Apple" and "Watermelon" before the tab. Tab-stop alignment depends on the terminal, so changing an item name can shift the price column.

Worked solution

Apple was changed to Pear. Each tab advances to the next tab stop, and each newline starts a new row. The displayed alignment of tabs depends on the terminal.

#include <iostream>

int main()
{
    std::cout << "Item\tPrice\n";
    std::cout << "Pear\t0.99\n";
    std::cout << "Banana\t1.25\n";
    std::cout << "Watermelon\t4.50\n";
    return 0;
}

Example output

This is one tested C++20 run. Sizes, capacity, formatting, floating-point details, or extra container lifetime messages may differ by implementation; use the explanation to identify the guaranteed result.

Item	Price
Pear	0.99
Banana	1.25
Watermelon	4.50

0 comments

No comments yet. Be the first.

Add a comment

About CppLearn

CppLearn is an interactive, free reference for modern C++. In each lesson, you'll find out how the language works, rather than just lines of code that you can copy and paste. We cover concepts starting from beginner lessons on fundamentals and proceed to templates, move semantics, smart pointers, and areas that usually trap or scare C++ learners.