Formatting Output with iomanip in C++
Raw cout output is unaligned and full-precision — fine for debugging, ugly for reports. The <iomanip> manipulators fix that: std::setw(n) pads the next item to width n, std::setprecision(n) controls significant digits (or decimals with std::fixed), std::left/std::right pick alignment, and std::setfill chooses the padding character.
The gotcha is stickiness: setw applies to the very next output only, while precision, fixed, and alignment persist until changed. Forgetting this produces one aligned column followed by chaos — set width fresh before every field.
setw: one-shot width
std::cout << std::setw(10) << name; pads name to 10 characters this once — the next item needs its own setw.
setprecision + fixed
std::fixed << std::setprecision(2) locks two decimals (19.99 style); without fixed, precision counts total significant digits instead.
Alignment and fill
std::left / std::right choose the side (right is default for numbers); std::setfill('*') pads with asterisks instead of spaces.
Remember what sticks
Only setw is single-use. fixed, precision, fill, and alignment persist for the rest of the stream until you reset them.
#include <iostream>#include <iomanip> int main() { std::cout << std::left << std::setw(8) << "Item" << "Price" << std::endl; std::cout << std::left << std::setw(8) << "Apple"; std::cout << std::fixed << std::setprecision(2) << 1.5 << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.