문제

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 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top