100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C++

Formatted Output in C++

Learn how to produce neatly aligned, formatted output in C++ using stream manipulators for width, precision, and alignment.

Input & OutputIntermediate6 min readJul 7, 2026
Analogies

1. Intro

Formatted output refers to controlling how data appears on the console — its width, alignment, number of decimal places, and padding — rather than printing raw values. C++ achieves this using stream manipulators from <iomanip> combined with stream format flags.

🏏

Cricket analogy: A scoreboard displaying '045*' with padded zeros controls exactly how the run count is presented, just as C++ formatted output controls width and padding rather than the raw number.

2. Syntax

cpp
cout << left << setw(15) << name << right << setw(8) << score << endl;

3. Explanation

By default, numeric output is right-aligned within its field width using setw, while left or right manipulators explicitly control alignment for text or numbers. fixed combined with setprecision(n) guarantees a consistent number of decimal places, which is essential for tables of prices or measurements. Formatted output is commonly used to build aligned tables in console applications, such as reports listing names alongside numeric scores or prices.

🏏

Cricket analogy: A scorecard right-aligns each batsman's run total within a fixed-width column using padding, just as setw right-aligns numeric output by default in C++.

When printing a table, remember that setw() only affects the next single field — reapply it before every column value in each row for consistent alignment.

4. Example

cpp
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    cout << left << setw(10) << "Item" << right << setw(8) << "Price" << endl;
    cout << left << setw(10) << "Apple" << right << setw(8) << fixed << setprecision(2) << 1.5 << endl;
    cout << left << setw(10) << "Bread" << right << setw(8) << fixed << setprecision(2) << 2.75 << endl;
    return 0;
}

5. Output

text
Item          Price
Apple          1.50
Bread          2.75

6. Key Takeaways

  • Formatted output controls width, alignment, and precision instead of printing raw values.
  • left and right manipulators set text alignment within a field.
  • fixed with setprecision(n) ensures consistent decimal-place formatting.
  • setw() must be reapplied before each field, including in table rows, since it does not persist.

Practice what you learned

Was this page helpful?

Topics covered

#CStudyNotes#Programming#FormattedOutputInC#Formatted#Output#Syntax#Explanation#StudyNotes#SkillVeris#ExamPrep