Question

I know how to set field width but only applying to the first element in the stream. For example.

cout << setw(5) << left << '1' << '2';

produces

1     2

and

cout << setw(5) << left << '1' << '2' << '3';

produces

1     23

How can I use the iomanip library to set the field width so that it applies to all elements producing

1     2     3

instead of writing setw(5) twice like below:

cout << setw(5) << left << '1' << setw(5) << left << '2' << '3';
Was it helpful?

Solution

Unfortunately, no. You must use setw() before almost every output operation. The problem is that operator<< effectively calls setw(0) after the output, thus you need to set width again. See here for a full list of operations that reset field width.

Note: setw is just a wrapper around width(), so using the latter won't help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top