难点在于,如果对齐方式要变化,需要先 reset。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << "------------------------------------" << endl;
// 14 9 13
cout << setiosflags(ios::left) << setw(14) << "Province" << resetiosflags(ios::left) // 用完之后清除
<< setiosflags(ios::right) << setw(9) << "Area(km2)" << setw(12) << "Pop.(10K)"
<< resetiosflags(ios::right) << endl;
cout << "------------------------------------" << endl;
string provinces[] = {"Anhui", "Beijing", "Chongqing", "Shanghai", "Zhejiang"};
string areas[] = {"139600.00", "16410.54", "82400.00", "6340.50", "101800.00"};
string pops[] = {"6461.00", "1180.70", "3144.23", "1360.26", "4894.00"};
for (int i = 0; i < 5; ++i) {
cout << setiosflags(ios::left) << setw(14) << provinces[i] << resetiosflags(ios::left)
<< setiosflags(ios::right) << setw(9) << areas[i] << setw(10) << pops[i]
<< resetiosflags(ios::right) << endl;
}
cout << "------------------------------------" << endl;
}