Given 2 numbers, print the first number as a 5-digit number and print the second number in the next line with 5 width space.
Explanation: If numbers are 25 and 98, print the first number as 00025 and second number as 3 space and 98( 98).
To format printed output, you need:
#include <iomanip>
This header gives you manipulators like setw
, setfill
, fixed
, etc.
setw()
sets the minimum total width of the next printed item.
Examples:
cout << setw(5) << 42;
→ " 42" (3 spaces on left)
✅ By default, padding is added on the left (right-aligned output).
❗ setw()
only affects the next item printed, then resets.
By default, setw()
uses spaces for padding. You can change it using setfill()
.
Example:
cout << setfill('0') << setw(5) << 42;
→ "00042"
✅ Once set, setfill()
stays active until you change it again.
Control where padding is added:
Manipulator | Pads On | Example (setw(6), 42) |
---|---|---|
right (default) |
Left side | " 42" |
left |
Right side | "42 " |
internal |
Between sign and digits | "-00042" |
Why internal matters:
cout << setw(6) << setfill('0') << internal << -42;
→ "-00042" ✅
Manipulator | Description |
---|---|
setw(n) |
Sets minimum field width |
setfill(ch) |
Changes padding character |
left |
Pads on right side |
right |
Pads on left side (default) |
internal |
Pads after sign, before digits |
💡 Tip: setw()
controls width, setfill()
controls padding character, and alignment controls where padding goes.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
long long a, b;
cin >> a >> b;
cout << internal << setfill('0') << setw(5) << a << endl;
cout << right << setfill(' ') << setw(5) << b;
return 0;
}