C++ New Lines
In this page:
std::cout << "text" << std::endl;
std::cout << "text\n";
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 std::cout and std::cin
#include <iostream>
// Program execution starts in main()
int main() {
// Print to the console with cout
std::cout << "Line one\nLine two\n";
// Return 0 to signal that the program finished successfully
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 std::cout and std::cin
#include <iostream>
// Program execution starts in main()
int main() {
// Print to the console with cout
std::cout << "Line one\n" << "Line two\n";
// Print to the console with cout
std::cout << "Line three" << std::endl;
// Return 0 to signal that the program finished successfully
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 std::cout and std::cin
#include <iostream>
// Program execution starts in main()
int main() {
// Print to the console with cout
std::cout << "Above" << std::endl << std::endl;
// Print to the console with cout
std::cout << "Below" << std::endl;
// Return 0 to signal that the program finished successfully
return 0;
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting
endlor\n, so successive outputs run together on one line. - Writing
/ninstead of\n, which prints a slash and an n rather than a new line. - Using
endleverywhere in loops, which also flushes the buffer and can slow output compared with\n.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: