C++ - C++ new line - Programming Languages

Creating a New Line in C++

How would code outputs look without line breaks? Each output would run together in an incomprehensible mess of words and numbers.  C++ offers a few ways to break outputs up into an easy-to-digest format.

Producing better-looking output allows the users of your program to better follow what’s happening. In this article we explore how to output text, what it means to break lines in C++, and the two ways to programmatically break lines.

What Is a New Line in C++?

When we output text in C++, we don’t always want all of the information to appear on one line. This can result in output that’s tough to read. The users of your program will have a tough time finding specific points in a large block of information, also known as the dreaded “wall of text”. 

A chunk of text, also known as a “string” to  C++ developers, is a sequential series of characters terminated by the special end-of-string character, written as ‘\0’. There are many other such special characters, such as tab `\t` and newline `\n` (the topic of this blog post).

Outputting Text in C++

There are a few crucial components you need to output text in C++. Understanding how you can use these components will help to break lines in output.

The cout Object

C++ uses the cout object to display information from code. It’s possible to use cout to output anything, from values of variables to strings:

cout << "The value of x is: " << x;

Even with multiple cout statements, the program won’t put the second statement on a second line:

...
int main()
{
    cout << "Hello! We want to output this text ";
    cout << "on two different lines.";
  return 0;
}

Try as we might, our program outputs everything on just one line:

Hello! We want to output this text on two different lines.

While the text appears on a single line, this is a straightforward output and is still easy to follow. Imagine how paragraphs of output would look without any formatting…

Similarly, a series of numbers can be hard to understand if displayed on the same line. The following for loop demonstrates this well:

...int main()
{
    for (int i = 0; i < 10; i++)
    cout << i;
    return 0;
}

This program returns ten different numbers all mashed together, rather than listing each individually:

0123456789

The Stream Extraction Operator (<<)

The << symbol is used to put together output parts (it’s also a left shift operator in bitwise operations). Technically,  << is a stream extraction operator, designating text as output or commands to be executed as the result of cout.

A single cout statement can have multiple extraction operators, each representing a specific function or output. The extraction operators further serve to break up different types of outputs:

...int main()
{
    int i = 3, j = 6;
    cout << "The value of i is: " << i << ". The value of j is: " << j;
  return 0;
}

This block of code returns the following:

The value of i is: 3. The value of j is: 6

You can see how cout combines different data types into one output.

How To Insert a Blank Line in C++

There are two ways to insert a blank line between text anywhere within a cout statement. Let’s take a look each of these ways:

The endl Function

The endl function, part of C++’s standard function library inserts a newline character into your output sequence, pushing the subsequent text to the next output line.

To add endl to a cout statement, you’ll have to add it after an extraction operator. Looking back at our earlier for loop example, we can use endl to output each number on a new line in C++:

...int main()
{
    for (int i = 0; i < 10; i++)
    cout << i << endl;
    return 0;}

Doing so gives us a significantly different output:

0
1
2
3
4
5
6
7
8
9

Note that endl must be free of quotation marks; otherwise, the program will treat it as a string.

The \n Character

The other way to break a  line in C++ is to use the newline character — that ‘\n mentioned earlier.

Unlike endl, \n must be within quotation marks. You can write “\n by itself, but you can also insert the newline sequence into the middle of a string:

...int main()
{
    cout << "This is line one.\nThis is line two.";
    return 0;
}

The program will recognize the escape function and create a new line accordingly:

This is line one.
This is line two.

Should you ever desire to output the literal \n as part of your string, escape the  escape sequence character:

...int main()
{
    cout << "This is line one.\\nThis is line two.";
    return 0;
}

The output is significantly different:

This is line one.\nThis is line two.

What Are the Differences Between \n and endl?

Although \n and endl perform essentially the same action, there are a few notable differences between the two commands.

Syntax

Endl and \n are significantly different in terms of syntax.

Because endl is a function, it must stand alone in a cout statement following an extraction operator (<<). You should not use endl with quotation marks, since that would cause the program to output endl as a string.

On the other hand, \n must appear either within double quotation marks (“ “) or single quotation marks (‘ ‘). You can place \n in the middle of a cout statement without having to insert any additional formatting. Failing to place \n in quotation marks will result in a compile error.

Here we see both new line commands used in the same block of code:

int main()
{
    cout << "This is line one.\nThis is line two." << '\n';
    cout << "This is line three." << endl << "This is line four." << endl;
    return 0;
}

With two cout statements, we get four lines of output:

This is line one.
This is line two.
This is line three.
This is line four.

\n Is Not Universal

Windows operating systems require both a line feed (\n) to move output to the next line and a carriage return (\r) to move the cursor back to the beginning of the line. Unix devices combine these two actions into the \n character, eliminating the need for a carriage return.

The code below would function as intended on a Unix machine:

...int main()
{
    cout << "This is line one.\nThis is line two." << '\n';
    return 0;
}

According to the C++ standard, using only \n on a Windows device can yield the following result:

This is line one.
                This is line two.

You need to add \r to push the second sentence back to the beginning of the line.

cout << "This is line one.\r\nThis is line two." << '\n';

However, many consoles and editors now know to treat \n as both a line feed and carriage return even on Windows systems. macOS C++ programmers need use only \n for both line feed and carriage return

Flushing the Output Stream

Each time a program executes the endl function, it also flushes the output buffer. Since pulling from the output buffer is time-consuming, having the program write an output every time endl is called adds a significant amount to run time.

\n does not flush the output buffer. Since cout automatically performs a flush, the program writes the entire output simultaneously, reducing run time.

For smaller code, you probably won’t notice the difference. Lengthy or cumbersome programs, however, will see a considerable difference.

The example below shows a for loop that increments a counter a total of 10,000,000 times. A built-in timer tracks how long the program takes to complete its run time: 

...int main() {

    auto begin = std::chrono::high_resolution_clock::now();

    int iterations = 10000000;
    for (int i = 0; i < iterations; i++) {
        cout << i << endl; // endl is replaced by '\n' to test the difference
    }

    auto end = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);

    printf("Time measured: %.3f seconds.\n", elapsed.count() * 1e-9);

    return 0;
}

Back-to-back runs using the same compiler but different new line commands resulted in the following times:

With endl: Time measured: 1279.024 seconds.
With \n: Time measured: 1225.650 seconds.


As you can see, the program using \n runs 45 seconds faster, but there isn’t an order-of-magnitude difference between the two run times.

Learn C++ Online With Udacity

As a programmer, you can use endl or \n to create new line commands in C++. These commands can make outputs much clearer to read and understand. Whether you ultimately use endl or \n depends on your operating system and the command’s placement in your code. Using new lines will help you on your journey to writing streamlined code.

Ready to take your next step toward becoming a C++ developer? 

Enroll in Udacity’s C++ Nanodegree program to learn the language by coding five real-world projects.

Complete Code Examples

Example 1: Two cout statements

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello! This is the ";
    cout << "text we want our users to see.";
  return 0;
}

Example 2: For loop

#include <iostream>

using namespace std;

int main()
{
    for (int i = 0; i < 10; i++)
    cout << i;
    return 0;
}

Example 3: endl and \n

#include <iostream>

using namespace std;

int main()
{
    cout << "This is line one.\nThis is line two." << '\n';
    cout << "This is line three." << endl << "This is line four." << endl;
    return 0;
}

Example 4: Large for loop with time counter

#include <stdio.h>
#include <chrono>
#include <iostream>

using namespace std;

int main() {

    auto begin = std::chrono::high_resolution_clock::now();

    int iterations = 1000000;
    for (int i = 0; i < iterations; i++) {
        cout << i << endl;
    }

    auto end = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);

    printf("Time measured: %.3f seconds.\n", elapsed.count() * 1e-9);

    return 0;
}