C++ New Lines

By default everything you print with cout appears on the same line. To move to a new line you need a special character or object. This page explains the two common ways to create new lines in C++.

Using \n

The \n character is called a newline. When it is included inside a text value, it tells the output to move down to the start of the next line. It is written as a backslash followed by the letter n.

New line with \n

#include <iostream>
using namespace std;

int main() {
  cout << "First line\n";
  cout << "Second line";
  return 0;
}

You can also place \n in the middle of a text value to split the output across multiple lines with a single cout statement.

Multiple new lines

#include <iostream>
using namespace std;

int main() {
  cout << "Line one\nLine two\nLine three";
  return 0;
}

Using endl

Another way to start a new line is the endl object. It moves the cursor to a new line and also flushes the output buffer, which means it forces any waiting text to be written immediately.

New line with endl

#include <iostream>
using namespace std;

int main() {
  cout << "Hello" << endl;
  cout << "World";
  return 0;
}

\n vs endl

Feature\nendl
Starts a new lineYesYes
Flushes the bufferNoYes
Typical speedFasterSlightly slower
Note: For most everyday output, \n is preferred because it is faster. Use endl only when you specifically need the output to be flushed right away.