CIS 150 - Output formatting

Objectives

  • Explain which libraries are needed for different purposes
  • Use C++ output formatting

Basic C++ output

  • To use the C++ I/O library: #include <iostream>
  • Specify elements/objects to be used:
    • Least correct (but easiest) [before main()]: using namespace std;
    • Better [before main()]: using std::cout;
    • Better still [at start of each function where cout is used]: using std::cout;
    • Best [when cout is actually used]: std::cout << "Hello world!\n";
  • Formatting the output is done using stream manipulators
  • The basic manipulators are included with the iostream library
  • Stream manipulators that take an argument (setprecision, setw, setfill) are in the iomanip library, so you must include it to use them
  • Specifying the manipulators to be used follows the same guidelines given above with the cout example

Basic output examples

string s1 = "Hello"; string s2 = "world"; int x = 5; int y = 37; cout << s1 << " " << s2 << "!\n"; cout << x << " + " << y << " = " << (x + y) << '\n';

Output formatting (manipulators)

  • setprecision(int): sets the number of digits printed (number of digits after decimal if "fixed" is also used)
  • setfill(char): sets fill character
  • left: left justifies output
  • right: right justifies output
  • hex: display output as hexadecimal
  • oct: display output as octal
  • dec: display output as decimal
  • fixed: set display mode on floating-point numbers to normal decimal point notation (not scientific notation)
  • showpoint: display decimal point on floating-point numbers even if number has no trailing significant digits
  • boolalpha: display booleans as true/false
  • noboolalpha: display booleans as 1/0
  • showbase: display leading "0" for octal numbers, leading "0x" for hexadecimal numbers
  • noshowbase: don't display leading "0" for octal numbers, leading "0x" for hexadecimal numbers
  • uppercase: display hexadecimal digits in uppercase

Output formatting notes and tips

  • Most of the manipulators remain in effect until changed, but setw is only valid for the next item output by the stream.
  • It is usually good practice when setting decimal positions using setprecision to use fixed and showpoint first.
  • Setting the width of output allows you to make neat columns of output.

Output formatting examples

double x = 12.348; int n = 15; cout << x << endl; // displays: 12.348 cout << fixed << showpoint << setprecision(2) << x << endl; // displays: 12.35 cout << setw(10) << n << endl; // displays: 8 spaces and 15 cout << x << endl; // displays: 12.348 cout << setfill('0') << setw(7) << n << endl; // displays: 0000015