C++ - Output & Printing
Overview
Estimated time: 20–30 minutes
Print text and numbers using std::cout. Learn newlines, basic manipulators, and formatting tips.
Learning Objectives
- Use std::cout with string and numeric values.
- Print new lines with '\n' and std::endl.
- Use iostream manipulators for simple formatting.
Prerequisites
Print text and numbers
#include <iostream>
int main(){
std::cout << "Hello, ";
std::cout << "world" << "!\n";
std::cout << 42 << '\n';
}
Newlines
std::cout << "line 1\nline 2\n";
std::cout << "line 3" << std::endl; // flushes the stream
Basic manipulators
#include <iomanip>
std::cout << std::setw(5) << 7 << "\n"; // pad width 5
std::cout << std::hex << 255 << "\n"; // hex output
Common Pitfalls
- Using std::endl for every newline can cause unnecessary flushing; prefer '\n'.
Checks for Understanding
- How do you print a newline without flushing?
Show answers
- Use '\n' instead of std::endl.
Exercises
- Print a table with two columns (left label, right value) using setw.