Output alignment has two aspects, one is the output width, one is left-justified or is also aligned.
In C + +, the default is right-aligned, can be adjusted to left-aligned by COUT.SETF (Std::ios::left), and this adjustment is global
, one set at a time, and the back is valid.
However, setting the output width (using the cout.width (int i) setting) is one-time, affecting only the one output immediately following it.
Refer to the following code for details:
#include <iostream>int main () {using STD::COUT;COUT.SETF (std::ios::left); int w = Cout.width (); cout << " Default Field width = "<< w <<" \ n "; cout.width (5); cout <<" n "<<": "; cout.width (8); cout << "N * n" << "\ n"; for (long i = 1; i <=; I *=) {cout.width (5); cout << i << ': '; cout.width (8); cout << i * << "\ n";} return 0;}
We can remove the code that adjusts the alignment direction (that is, with the default right alignment setting), and the output is as follows after re-running:
You can carefully observe the distance between the number of seats and the colon. When using right-aligned, the left number is next to the colon, while left-justified, the left-hand number is output 5 characters wide before the colon is output (again, the width setting affects only one output.) This is the output that affects only n, without affecting the output of the colon. )
In this regard, C language is much simpler, printf ("%5d"), output occupies 5 characters width, and right alignment, printf ("%-5d") output occupies 5 character width, and left-aligned. When it's time to set it up.
Another question is, what happens when the actual data needs to be wider than the width you set?
The choice of C + + is to ensure that the data is displayed intact.
For example, the 8th line in the above program:
cout << "N" << ":";
We modify it into
cout << "nnnnn" << ":";
The discovery output is as follows:
At this point, the data is exactly 5 characters justifies, can still be aligned, but we add another n, as follows:
cout << "nnnnnn" << ":";
Have you found that it is not right. So the C + + Chinese priority guarantees the data display complete.
The C language uses printf in fact the same, giving priority to ensuring that the data is displayed intact.
Output alignment settings in C + +