Output Basics
Lesson outline
Understanding C++ Output
In C++, the std::cout object from the library is used with the insertion operator (<<) to display output.
Key features:
- Streams automatically format many built-in types to human-readable text
- Output is buffered for performance (not immediately written to the terminal)
- You can chain multiple insertions in a single statement
"\n"inserts a newline without flushing;std::endlinserts a newline and flushes (use it only when you need a flush)
Basic Output with Formatting
Here's a clean example showing basic output and a newline:
Advanced Output Techniques
More sophisticated output examples with different data types:
Newlines and Flushing
Prefer '\n' for newlines in most cases; it does not flush. Use std::endl or std::flush only when you explicitly need a flush (e.g., before waiting for user input or showing progress).
Professional Output Practices
For production-quality code:
- Format numbers consistently (
:std::setw,std::setfill,std::setprecision,std::fixed,std::scientific) - Avoid
using namespace std;in global scope; qualify withstd:: - Consider localization when appropriate
- Separate presentation logic from business logic
- Use constants for repeated strings for consistency
Number Formatting with
Use manipulators to control precision, notation, alignment, and boolean text:
cout vs cerr vs clog
std::cout is for regular output, std::cerr is unbuffered (good for errors), and std::clog is buffered diagnostics.
Keep error messages on std::cerr so they appear promptly and remain separate from normal program output.
Performance Tip
If you only use iostreams (no printf/scanf), you can speed up I/O by disabling sync with stdio and detaching cin from cout: