Absolute Beginners C++


Lesson 6 - Output formatting

6.1 Integer output formatting

// ex6-1.cpp - Integer output formatting
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    cout << "Enter an integer : ";
    int ival;
    cin >> ival;
    cout << "Normal  : " << ival << endl;
    cout << "Right 10: " << setw(10) << ival << endl;
    cout << "Base   8: " << setbase(8) << ival << endl;
    cout << "Base  16: " << setbase(16) << ival << endl;
    return(0);
}
ex6-1
Enter an integer : 27
Normal  : 27
Right 10:         27
Base   8: 33
Base  16: 1B
Example ex6-1 demonstrates some capabilities of the 'cout' object for formatting how integer numbers are printed.  In earlier examples, we have let cout format numbers in its standard or 'default' way.  This was to print as few digits as possible, with no leading or trailing spaces.  If you want your numbers to be right-aligned, so as to make a column of numbers where the units column lines up for example, it is necessary to precede the digits with a variable number of spaces depnding on the size of the number.  The 'setw(10)' instruction to cout tells it to output numbers in a 'field' of width 10: that is to right align the numbers with enough spaces to make the overall number of characters output equal to 10. 
This example also shows how the number base can be changed.  Internally numbers are stored in the computer as base 2 values (binary), and the computer converts them to base 10 by default when it prints them.  If we want our numbers printed in base 8 or in base 16 (say), then the instruction 'setbase(8)' or 'setbase(16)' tells cout to change the base for the next number to be output. 
Note that to use the output formatting capabilities of cout, you need to include the standard declarations in the file 'iomanip', with the instruction '#include <iomanip>'. 
 

6.2 Fractional number output formatting

// ex6-2.cpp - Fractional number formatting
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    cout << "Enter a fractional number : ";
    double dval;
    cin >> dval;
    cout << "Normal    : " << dval << endl;
    cout << "Right 10  : " << setw(10) << dval << endl;
    cout << "Fixed 10.3: " << setiosflags(ios::fixed) 
        << setw(10) << setprecision(3) << dval << endl;
    cout << "Scientific: " << setiosflags(ios::scientific)
        << setw(10) << setprecision(3) << dval << endl;
    return(0);
}
ex6-2
Enter a fractional number : 12345.6
Normal    : 12345.6
Right 10  :    12345.6
Fixed 10.3:  12345.600
Scientific:  1.23e+004
Formatting of fractional numbers is shown in example ex6-2.  In this program there are two new instructions to control the formatting of fractional numbers (otherwise known as 'floating point numbers').  The instruction 'setw(width)' operates as before, setting the field with to a given number of characters.  The instruction 'setiosflags(ios::fixed)' is a complex way of asking for the numbers to printed with a fixed number of decimal places, while the instruction 'setiosflags(ios::scientific)' is how you ask for numbers to be printed in scientific notation, with an exponent.  The instruction 'setprecision(3)' sets the accuracy with which numbers are printed.  For fixed format, the precision is the number of decimal places; while for scientific format the precision is the total number of digits in the number.  Thus, in the example, with a precision of 3, the fixed format has 3 decimal places, while the scientific format has only 3 figures altogether.

6.3 String output formatting

// ex6-3.cpp - String output formatting
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
    cout << "Enter a string : ";
    string sval;
    cin >> sval;
    cout << "Normal  : '" << sval << "'" << endl;
    cout << "Right 10: '" << setw(10) 
         << sval.c_str() << "'" << endl;
    cout << "Left  10: '" << setiosflags(ios::left) 
         << setw(10) << sval.c_str() << "'" << endl;
    return(0);
}
ex6-3
Enter a string : Hello
Normal  : 'Hello'
Right 10: '     Hello'
Left  10: 'Hello     '
Example ex6-3 shows how the output formatting instructions extend to strings of characters.  By default, cout outputs a string of characters with no leading or trailing spaces.  Once again, the 'setw(width)' instruction can be used to create a field with within which the output is right aligned: that is preceded by spaces so as to make the total number of characters output equal to 'width'.  To left align a string into a field, it is necessary to use the instruction 'setiosflags(ios::left)' preceding the output of the string.  One additional complication is shown in the example.  The cout object cannot actually align objects of type string at all, so they need to be converted to a more primitive type of string first.  This type of string is called a 'C-string' because it harks back to the 'C' language way of dealing with strings.  To convert our C++ strings into C strings is actually very easy, we just ask our string objects to convert themselves by appending '.c_str()' to their name.  Thus the instruction 'sval.c_str()' in the program is a request to the C++ string object 'sval' to return a C-string copy of itself to pass on, in this case, to cout.

6.4 Exercises

a. Write a program (bill.cpp) that takes as input your current and previous electricity meter reading and calculates how much you owe assuming that units cost 11.5p each. Lay out the report neatly, as in: 
bill
Enter new meter reading : 1234
Enter old meter reading : 1034
******************************
Number of units used:      200
Cost of each unit:       0.115
Total cost:              23.00
******************************

b. Write a program (wd3sort.cpp) that reads in three words and reports them back in alphabetical order, prefixed by their position and right aligned, as in:

wd3sort
Enter word 1 : Charlie
Enter word 2 : Bert
Enter word 3 : Alfred
Sorted Order
First:       Alfred
Second:        Bert
Third:      Charlie


© 1999 Mark Huckvale University College London