9. Format Numbers with Width and Fill

Medium ⏱️ 10 min

Description

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).

Input Format:
Accept the two integer as a input
Output Format:
5 digit number format followed by number with 5 width space in new line.
Constraints:
10^-15 ≤ num1,num2 ≤ 10^15
Sample Input 1:
34 7896
Sample Output 1:
00034 7896
Sample Input 2:
-125 -36
Sample Output 2:
-0125 -36
🧱 C++ Output Formatting Guide
📚 The <iomanip> Library

To format printed output, you need:

#include <iomanip>

This header gives you manipulators like setw, setfill, fixed, etc.

📏 setw(n) — Set Width

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.

🔢 setfill(ch) — Set Fill Character

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.

↔️ Alignment Manipulators

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" ✅

📊 Quick Reference Table
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.

Solution

#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;
}