C++: I/O Operations -2

Formatted Console I/O Operations

To access manipulators the file iomanip should be included in program.

cout.width(w); to define width of a field necessary for output of item.
w is field width(no. of columns)

cout.precision(d)to specify no. of digits to be displayed after the decimal point.

By default, floating no. are printed with six digits after the decimal point.

  cout.precision(3);
  cout<<3.15159<<"\n";
  cout<<2.50032<<"\n";

3.142(rounded to nearest cent)
2.5 (no trailing zeros)

Unlike width(), precision() retains the setting in effect until it is reset.

cout.fill(ch);  to fill unused position by any desired character.

By default, the unused positions of the field are filled with the white spaces.

  cout.fill("*");
  cout.width(10);
  cout<<5250<<"\n";

******5250

fill() also stays in effect till we change it.

cout.setf(arg1,arg2); 
arg1 is one of the formatting flags specifies the format action required for output.
arg2 is known as bitfield specifies the group to which the formatting flag belongs.

  cout.setf(ios::left,ios::adjustfield);
  cout.setf(ios::scientific,ios::floatfield);

__________________________________________

Managing Output with Manipulators

Some manipulators in the class iomanip are more convenient to use than their counterpart in the class ios.

  Manipulators                Equivalent in ios
    setw(int w)                     width()
    setprecision(int d)         precision()
    setfill(int c)                      fill()
    setiosflags(long f)         setf()
    resetiosflags(long f)      unsetf()
    Endif                                  "\n"

Designing our own Manipulators

  ostream & manipulator(ostream & output)
  {
    .......
    .......
   return output;
  }

Here the manipulator is the name of the manipulator under creation.

Eg:

  ostream & unit(ostream & output)
  {
    output<<"inches";
    return output;
  }

The output of statement
  cout<<36<<unit;
is
36 inches.
__________________________________________

   < Happy Coding >

Reference:
OOP by BALAGURUSWAMY
In Association with Amazon.in

Comments

Popular Posts

Top 10 Web Sites Every Programmer Should Visit Daily

How do I improve my logical thinking and problem solving skills?

C++: STL Iterators