John Humphreys
John Humphreys

Reputation: 39294

What does the combination of setf(ios::left, ios::adjustfield) do?

I was reading a textbook and I came across this line.

It seems to format output prettily in two columns (I'm guessing the left one get set width making the right one look even since it all starts at the same column). I'm not too sure about what the line is really doing though.

cout.setf(ios::left, ios::adjustfield);

Can someone explain this to me?

Upvotes: 4

Views: 9075

Answers (1)

Chad
Chad

Reputation: 19032

It forces text in a fixed width field to be output with left justification. See this reference. This is using the second override of that function that takes in the mask in which to set the particular flags.

This override will clear any existing flags that are set in std::ios_base::adjustfield, which handles justification of text output through a stream object.

The override that doesn't take the flag mask (second parameter) will simply additionally set the flag specified, which doesn't make a lot of sense in the case of adjustfield since the valid values are only left, right, and internal, which all deal with text justification.

Hopefully this small example will make it clear:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
   cout.setf(std::ios::left, std::ios::adjustfield);
   cout << setfill('^') << setw(10) << "Hello" << "\n";

   cout.setf(std::ios::right, std::ios::adjustfield);
   cout << setfill('0') << setw(10) << "99\n";

   return 0;
}

It gives the output:

Hello^^^^^
000000099

Upvotes: 6

Related Questions