[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Stream Iterators Up: Input/Output Previous: Simple I/O

Formatting

The way that text and numbers are output can be controlled.
[fontsize=\small,frame=single,formatcom=\color{progcolor}]
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main()
{
  int i=10;
  cout << "i = " << i << " (default)\n" ;
  cout << hex << "i = " << i << " (hex)\n";

  double d = sqrt(7.0);
  cout << "d=sqrt(7.0)=" << d << endl;
  cout.precision(3);
  cout << "After cout.precision(3), d=" << d << endl;

  return 0;
}

There many other routines too, amongst them

cout.setf(ios_base::oct,ios_base::basefield); // set base to 8

const ios_base::fmtflags myopt = ios_base::left|ios_base::oct;

ios_base::fmtflags old_options = cout.flags(myopt); //set base to 8
// and alignment to left.

cout.precision(8); // set precision to 8
cout.setf(ios_base::scientific, ios_base::floatfield);

cout.width(4);  // output at least four characters
cout.fill('*'); // fill gaps with '*'
cin.noskipws(); // don't skip white space



Tim Love
2001-07-05