C++ New Lines

In C++, displaying text neatly is crucial for readability. To insert a new line in your output, you can use special characters and operators.



Using \n to Break Lines

The newline character (\n) moves the cursor to the next line when printing text.

#include <iostream>
using namespace std;

int main() {
  cout << "Motorcycles bring freedom! \n";
  cout << "Ride with passion.";
  return 0;
}

Another Way to Use \n

You can also place \n outside the text by using another << operator:

#include <iostream>
using namespace std;

int main() {
  cout << "Motorcycles bring freedom!" << "\n";
  cout << "Ride with passion.";
  return 0;
}




Creating a Blank Line

If you place two \n characters together, it creates an extra empty line:

#include <iostream>
using namespace std;

int main() {
  cout << "Motorcycles bring freedom!" << "\n\n";
  cout << "Ride with passion.";
  return 0;
}




Using endl

Another way to insert a new line is by using the endl manipulator, which functions like \n:

#include <iostream>
using namespace std;

int main() {
  cout << "Motorcycles bring freedom!" << endl;
  cout << "Ride with passion.";
  return 0;
}




\n vs endl

Both \n and endl create new lines, but \n is more commonly used because it works efficiently without requiring extra processing.

\n is an escape sequence that forces the cursor to move to the beginning of the next line.

Other Useful Escape Sequences:

Escape SequenceDescription
\tCreates a horizontal tab (adds space)
\\Inserts a backslash (\)
\"Inserts a double quote (")
Scroll to Top