Learn C++
#include "ioformatting/manipulators.hpp"

Formatting Output with iomanip in C++

//concept

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.

//how it works
1

setw: one-shot width

std::cout << std::setw(10) << name; pads name to 10 characters this once — the next item needs its own setw.

2

setprecision + fixed

std::fixed << std::setprecision(2) locks two decimals (19.99 style); without fixed, precision counts total significant digits instead.

3

Alignment and fill

std::left / std::right choose the side (right is default for numbers); std::setfill('*') pads with asterisks instead of spaces.

4

Remember what sticks

Only setw is single-use. fixed, precision, fill, and alignment persist for the rest of the stream until you reset them.

//example
#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;
}
Output
Item Price
Apple 1.50
1setw(8) pads Item to 8 characters so Price starts in a neat column — left alignment keeps text tidy.
2A fresh setw(8) is needed for Apple since the first one expired after a single use.
3fixed + setprecision(2) prints 1.5 as 1.50, the money format, and persists for later numbers.
//use cases
Printing aligned tables and receipts in console programs
Money and measurement output locked to two decimals with fixed + setprecision
Zero-padded IDs and timestamps via setfill('0') + setw
Debugging float noise by capping displayed precision

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.