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

I/O Manipulators in C++

Explore C++ I/O manipulators from `<iomanip>` like `setw`, `setprecision`, `setfill`, and `fixed` used to control stream formatting.

Input & OutputIntermediate7 min readJul 7, 2026
Analogies

1. Intro

I/O manipulators are special functions that alter the formatting behavior of input/output streams when inserted into cin or cout using << or >>. Some manipulators, like endl, are declared in <iostream>, while more advanced ones, like setw and setprecision, require the <iomanip> header.

🏏

Cricket analogy: A scoreboard operator has basic tools built into the stadium display, like showing the over count, but needs a special add-on panel for advanced stats like strike rate — just as endl ships with <iostream> while setw needs <iomanip>.

2. Syntax

cpp
cout << setw(10) << value;
cout << setprecision(3) << value;
cout << setfill('*') << setw(10) << value;
cout << fixed << setprecision(2) << value;

3. Explanation

setw(n) sets the minimum field width for the next output item only, right-aligning it by default. setprecision(n) controls the number of significant digits shown for floating-point numbers, or, combined with fixed, the number of digits after the decimal point. setfill(c) sets the character used to pad fields when setw widens them (space is the default). fixed forces floating-point numbers to be displayed in fixed-point notation rather than scientific notation. endl inserts a newline and flushes the output buffer, whereas "\n" inserts a newline without flushing, making "\n" faster for high-volume output.

🏏

Cricket analogy: setw(n) is like padding a scorecard column so 'MS Dhoni' and 'Virat Kohli' line up neatly; setfill('*') decides the padding character, setprecision rounds the batting average to two decimals, fixed locks that format, and endl flushes the printed sheet immediately while \n just breaks the line.

setw() applies only to the very next inserted value — it must be repeated before every field that needs the width applied, unlike setprecision or fixed, which remain in effect until changed.

4. Example

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

int main() {
    double pi = 3.14159265;

    cout << setw(10) << setfill('*') << 42 << endl;
    cout << fixed << setprecision(2) << pi << "\n";
    return 0;
}

5. Output

text
********42
3.14

6. Key Takeaways

  • setw(n) sets width for only the immediately following output value.
  • setprecision(n) controls significant digits, or decimal places when combined with fixed.
  • setfill(c) changes the padding character used with setw.
  • endl flushes the buffer; "\n" does not, making "\n" more efficient for frequent output.

Practice what you learned

Was this page helpful?

Topics covered

#CStudyNotes#Programming#IOManipulatorsInC#Manipulators#Syntax#Explanation#Example#StudyNotes#SkillVeris#ExamPrep