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';
Unfortunately, no. You must use
setw()
before almost every output operation. The problem is thatoperator<<
effectively callssetw(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 aroundwidth()
, so using the latter won't help.