C++ New Lines
In this page:
The endl Manipulator
endl is a C++ stream manipulator that moves output to a new line and also flushes the output buffer, guaranteeing the text printed so far is actually written out immediately.
Example: The endl Manipulator
#include <iostream>
int main() {
std::cout << "Line one" << std::endl; // moves to new line and flushes
std::cout << "Line two" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The \n Escape Sequence
The \n escape sequence, inherited from C, represents a newline character and can be embedded directly inside a string literal to move output to a new line at that exact point.
Example: The \n Escape Sequence
#include <iostream>
int main() {
std::cout << "Line one\nLine two\n";
return 0;
}
Login to try C/C++/Java/PHP code in the editor
endl vs \n
Unlike endl, \n only inserts the newline character without forcing a buffer flush, which makes it the faster choice when printing many lines in a tight loop.
Example: endl vs \n
#include <iostream>
int main() {
for (int i = 0; i < 3; i++) {
std::cout << i << "\n"; // faster: no forced flush each iteration
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Multiple Lines in One Statement
Multiple lines of output can be built either by chaining several \n-terminated strings in one cout statement, or by using separate cout statements each ending in endl.
Example: Multiple Lines in One Statement
#include <iostream>
int main() {
std::cout << "Line one\n" << "Line two\n";
std::cout << "Line three" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Blank Lines
A blank line between two pieces of text is produced by two consecutive newlines, whether written as two chained endl manipulators or two \n characters next to each other in a string.
Example: Blank Lines
#include <iostream>
int main() {
std::cout << "Above" << std::endl << std::endl;
std::cout << "Below" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: