get ideas:1.按列排序,可以根據橫縱座標來求下標:int cols = (maxcol - M) / (M + 2) + 1, rows = (n - 1) / cols+ 1;
2.除了用製表符/t外,可以通過補空的方式輸出表格
cout << s;
for(int i = 0; i < len-s.length(); i++)
cout << extra;
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
const int maxcol = 60;
const int maxn = 100 + 5;
string filenames[maxn];
//輸出字符串s,長度不足len 時補字符extra
void print(const string& s, int len, char extra)
{
cout << s;
for(int i = 0; i < len-s.length(); i++)
cout << extra;//extra傳值是一個空格
}
int main()
{
int n;
while(cin >> n) {
int M = 0;
for(int i = 0; i < n; i++)
{
cin >> filenames[i];
M = max(M, (int)filenames[i].length()); //filenames[i].length()是unsigned int 類型,所以要強制轉換爲int型
} //計算列數cols 和行數rows
int cols = (maxcol - M) / (M + 2) + 1, rows = (n - 1) / cols + 1;//無論如何總會有一行
print("", 60, '-');
cout << "\n";
sort(filenames, filenames+n); //排序
for(int r = 0; r < rows; r++)
{
for(int c = 0; c < cols; c++)
{
int idx = c * rows + r;
if(idx < n) print(filenames[idx], c == cols-1 ? M : M+2, ' ');
}
cout << "\n";
}
}
return 0;
}