Title: Formatted Output Examples
Course: CPS 120: Introduction to Computer Science ~ Master (Aug/2015) OLD > Section: Learning Units

Example 1: format some columns

cout << setw(30) << right << "This is right-justified."
<< "Here is the next item" << endl;
cout << setw(30) << left << "This is left-justified."
<< "Here is the next item" << endl;

cout << endl << endl;
cout << setw(19) << " "
<< "Presidential Birthdates" << endl;
cout << setfill('=');  // Turn on equal signs
cout << setw(62) << "=" << endl << endl;

cout << setfill(' ');  // Turn off equal signs
cout << setw(21) << left << "Last"
<< setw(21) << left << "First"
<< setw(20) << right << "Birthdate" << endl;

cout << setfill('-');  // Turn on dashes
cout << setw(20) << left << "-"
<< setw(21) << left << " "
<< setw(21) << left << " " << endl;

cout << setfill(' ');  // Turn off dashes
cout << setw(21) << left << "Washington"
<< setw(21) << left << "George"
<< setw(20) << right << "22 February 1732" << endl;

cout << setw(21) << left << "Lincoln"
<< setw(21) << left << "Abraham"
<< setw(20) << right << "12 February 1809" << endl;

Example 1 output

Example 2: format some numbers ("\t" represents the tab character)

cout << setw(30) << left << "Default formatting:"
<< 35. << "\t" << 45.123 << "\t\t"
<< 55.123456 << "\t\t" << 65.123456789 << endl;

cout << fixed;
cout << setw(30) << left << "Fixed (precision is 6):"
<< 35. << "\t" << 45.123 << "\t"
<< 55.123456 << "\t" << 65.123456789 << endl;

cout << fixed << setprecision(2);
cout << setw(30) << left << "Fixed, Setprecision(2):"
<< 35. << "\t" << 45.123 << "\t\t"
<< 55.123456 << "\t\t" << 65.123456789 << endl;
cout.unsetf(ios::fixed); cout << setprecision(0);
cout << setw(30) << left << "Default formatting:"
<< 35. << "\t" << 45.123 << "\t\t"
<< 55.123456 << "\t\t" << 65.123456789 << endl;

Example 2 output