Use of ios::left and ios::right

From Prof. Schmolze on 10/4/2002.

To all COMP 11 students but especially to those in Section 2, I make the following clarification about the use of these flags when writing to cout. Unfortunately, I only just realized precisely how they operate.

As a result, the answer to question 2b in teh study guide for exam 1 is misleading. I was not trying to be tricky--I simply made an error. The output attempts to print 20 right justified in a field of width 6, then 3 left justified in a field of 5, and finally the word 'end'. Instead, the second value, 3, is right justified, as shown in the answer key.

The code from the study guide that prints these values is:

  cout << setiosflags(ios::right) << setw(6) << n;
  cout << setiosflags(ios::left)  << setw(5) << m;
  cout << "end" << endl;
which produced
Here I use the character ^ to represent a space.

Instead I should have written:

  cout << setw(6) << n;
  cout << setiosflags(ios::left)  << setw(5) << m;
  cout << "end" << endl;
to produce

The text says to use 'left' and 'right' to control left and right justification in your output. E.g., to print a value right justified, don't do anything special.

   int i=123;
   cout << "|" << setw(5) << i << "|" << endl;
prints as follows:
To print the same value left-justified:
   cout << "|" << setw(5) << left << i << "|" << endl;
The left justification is "sticky" -- all values printed afterwards are left justified until you do:
  cout << right;

Our C++ compiler does not recognize the commands 'left' and 'right'. Instead you use 'setiosflags(ios::left)' to begin left justification and use 'resetiosflags(ios::left)' to return to right justification. Do not use 'setiosflags(ios::right)' at all, even though it is legal to do.

In this example, I print right justified, then left justified and finally right justified again.

  cout << "|" << setw(5) << i << "|" << endl;
  cout << "|" << setw(5) << setiosflags(ios::left) << i << "|" << endl;
  cout << "|" << setw(5) << resetiosflags(ios::left) << i << "|" << endl;
I hope this helps.
James G. Schmolze
Last modified: Sat Oct 5 00:25:06 EDT 2002