[cs13001] cout.setf meaning

Mikhail Nesterenko mikhail at cs.kent.edu
Sat Sep 29 17:08:07 EDT 2012


> 
> I still haven't started reading the latest CS lectures, I was
> reading in the book about previous lessons, and I stumbled across
> this:

These are so called output stream manipulators. They format how the
output comes out. In this case the manipulators format the output of
floating point (double) numbers. In this course, we do not focus on
output formatting, so you are free to use or not to use them.

> 
> cout.setf(ios::fixed);

This one says that the double numbers should always be printed in
fixed (rather than scientific) notation.


> cout.setf(ios::showpoint);

The decimal point is shown regardless of whether the fractional part
is zero or not.

> cout.precision(2)

In fixed notation it states how many digits are to be printed after
the decimal point. If the number to be printed has more digits, it is
rounded.

This example program:

-----------------
// example output manipulators
// Mikhail Nesterenko
// 9/29/2012

#include <iostream>
#include <iomanip>

using namespace std;

int main(void){
  int a = 1;
  double b = 1.;
  double c = 1234567.899;

  cout << a << ' ' <<  b << ' ' << c << endl;

  cout.setf(ios::fixed);
  cout << a << ' ' <<  b << ' ' << c << endl;

  cout.setf(ios::showpoint);
  cout << a << ' ' <<  b << ' ' << c << endl;

  cout.precision(2);
  cout << a << ' ' <<  b << ' ' << c << endl;
}
----------------------

produces this output:

----------------------
1 1 1.23457e+06
1 1.000000 1234567.899000
1 1.000000 1234567.899000
1 1.00 1234567.90
----------------------

Thanks,
--
Mikhail





More information about the cs13001 mailing list