DevAcademia lesson/C++ Basics
New Lines
Topic progressTopic 7 of 109 - 6% complete
~10 min lesson24 learning blocks3 code examples1 checks/interactions
Lesson outline
Line Control Fundamentals
Effective line control is essential for readable console output. C++ offers multiple methods, each with specific use cases:
\n: Newline character (does not flush the stream).std::endl: Inserts a newline and flushes the stream buffer.\r: Carriage return (moves the cursor to the start of the current line; useful for in-place updates like progress bars).std::flush: Flushes the stream without adding a newline.std::ends: Inserts a\0(null) character and flushes—rarely needed for modern text output.- Multiple newlines: Print
"\n\n"etc. to separate sections.
Practical \n Examples
Common patterns using \n:
Advanced Formatting Techniques
Creating professional-looking output layouts and in-place updates:
Performance Considerations
Flushing on every line is expensive. Compare \n (no flush) vs. std::endl (flush) by writing to a file:
Line Endings & Text Mode
C++ \n represents a logical newline. In text mode, the implementation may translate it to the platform's native line ending (e.g., \r\n on Windows).
On binary streams (opened with std::ios::binary), no translation occurs. Use \n in your code; let the implementation handle text-mode translation.
Professional Recommendations
For production code:
- Use
\nby default for performance. - Reserve
std::endl(orstd::flush) for points where output must be visible immediately (e.g., before blocking on input). - For progress bars, pair
\rwithstd::flushand pad with spaces to fully overwrite prior text. - Avoid
\tfor alignment; use(std::setw,std::left/right) for consistent columns. - In multi-threaded apps, serialize output to avoid interleaving (e.g., guard with a mutex).
- Excessive console output can be a bottleneck—log to files or aggregate messages when possible.
Was this topic clear?