Generating proper output to terminal and files

 

To control the display properties of output through cout or while writing to a file, you can use a few manipulators. As a brief example suppose you want to compute a multiplication table. In the example below, results of multiplication range between 1 and three digit numbers. Therefore to align the output properly we need to define a minimum length so that every output would be of same length (and thus if shorter, be padded with extra spaces).

 

#include<fstream>
#include<string>
#include<iostream>
using namespace std;

int main (void)
{

    string filename;
    ofstream out;
    cout << "output filename ";
    cin >> filename;
    out.open(filename.c_str());
    int table[10][10];
    for (int i=0;i<10;i++)
     {
        for (int j=0;j<10;j++)
            {
                table[i][j]=(i+1)*(j+1);
                out.width(4);
                out << table[i][j];
               }//J for
        out << endl;
    }//I for
    out.close();
    return (0);
}//main
 

In the above example, numbers are aligned right. Using setf, you can change the alignment to the left. Adding the following line, will generate a different output as shown below.

out.setf(ios::left);


This is so far enough to generate a nice looking table. For those of you interested, cout can add some more display flexibility. By default, floating point numbers are printed in general format, Scientific notation is used when necessary to show the significant digits (6 by default), fixed point format otherwise. For example,

      cout << 123.456789 << ' ' << 123456789; 

prints 123.457 1.23457e+007. (You can get an uppercase E by setting ios::uppercase).

You can explicitly choose either scientific or fixed format with the ios flags scientific or fixed.

      cout << setiosflags(ios::fixed);
      cout.setf(ios::scientific);

To reset to general format, there isn't a flag ios::general. Instead, you must use

      cout << resetiosflags(ios::floatfield);

or

      cout.unsetf(ios::floatfield);

To see a + sign for positive numbers, use ios::showpos. (This also works for integers.) To see trailing zeros, use ios::showpoint . For example,

      cout.setf(ios::fixed | ios::showpoint | ios::showpos);
      cout << 123.456;

prints +123.456000.

You can change the precision from the default 6.

      cout << setprecision(10) << 123.45678 

or

      cout.precision(10);
      cout << 123.45678

prints 123.45678.

Find more details here.

The University of Southern California does not screen or control the content on this website and thus does not guarantee the accuracy, integrity, or quality of such content. All content on this website is provided by and is the sole responsibility of the person from which such content originated, and such content does not necessarily reflect the opinions of the University administration or the Board of Trustees