Skip to main content

ios class functions and flags for formatted I/O

Short answer

ios functions width(n) sets next field width; precision(n) sets digits; fill(c) sets pad char; setf(flags) and unsetf(flags) manage flags. Format flags include left/right, dec/oct/hex, showbase, showpoint, showpos, fixed/scientific, uppercase, boolalpha.

What are the different ios class functions and flags that are used for formatted I/O operation? Explain with usage.

The ios class (base of all stream classes) provides member functions and format flags to control formatted I/O.

Member functions

FunctionUse
width(n)Sets minimum field width for the next output only
precision(n)Sets number of digits (decimal places with fixed)
fill(ch)Sets padding character
setf(flags)Turns on format flags
unsetf(flags)Turns off format flags

Format flags (used with setf)

FlagEffect
ios::left, ios::right, ios::internalJustification in field
ios::dec, ios::oct, ios::hexNumber base
ios::showbaseShows 0x or 0 prefix
ios::showpointShows trailing decimal point/zeros
ios::showposShows + for positive numbers
ios::fixed, ios::scientificFloating point notation
ios::uppercaseUpper case in hex/exponent
ios::boolalphaPrints true/false

Usage

#include <iostream>
using namespace std;
int main() {
    cout.fill('*');
    cout.width(10);
    cout.setf(ios::left);
    cout << "Ram" << endl;              // Ram*******

    cout.unsetf(ios::left);
    cout.setf(ios::fixed, ios::floatfield);
    cout.precision(2);
    cout.width(10);
    cout << 3.14159 << endl;            // ******3.14

    cout.setf(ios::hex, ios::basefield);
    cout.setf(ios::showbase);
    cout << 255 << endl;                // 0xff
    return 0;
}

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 8 questions →