c++文件对齐

头文件#include <iomanip>

关键词:setw(n),std::left,std::right

实例:输出一个0-4的12*12方阵,要求数字宽度为4,居左对齐,右下角输出出品人、时间、运行时间居右对齐。

代码:

 1 #include <iostream>
 2 #include <ctime>
 3 #include <iomanip>
 4 using namespace std;
 5 int main()
 6 {
 7     srand((unsigned)time(NULL));
 8     int p[12][12] = { 0 };
 9     for (int i = 0; i < 12; i++)
10     {
11         for (int j = 0; j < 12; j++)
12         {
13             p[i][j] = rand() % 5;
14         }
15     }
16     for (int i = 0; i < 12; i++)
17     {
18         for (int j = 0; j < 12; j++)
19         {
20             cout <<std::left<< setw(4) << p[i][j];
21         }
22         cout << endl;
23     }
24     time_t now = time(0);
25     char *t = ctime(&now);
26     cout << std::right << setw(45) << "出品人:会武术之白猫" << endl;
27     cout << std::right << setw(46) << t << endl;
28     cout << std::right << setw(41) << clock() / CLOCKS_PER_SEC * 1000 << "毫秒" << endl;
29 }

结果:

一个setw和std::right只对后边一个变量有效,切记。

原文地址:https://www.cnblogs.com/ljy1227476113/p/9737334.html