Unix is 命令

输入正整数n以及n个文件名,排序后按列优先的方式左对齐输出。假设最长文件名有M字符,则最右列有M字符,其他列都是M+2字符。

附加条件每行最多输出60个字符,在此条件下要求行最少。

Sample input

10
tiny
2short4me
very_long_file_name
shorter
size-1
size2
size3
much_longer_name
12345678.123
mid_size_name
12
Weaser
Alfalfa
Stimey
Buckwheat
Porky
Joe
Darla
Cotton
Butch
Froggy
Mrs_Crabapple
P.D.
19
Mr._French
Jody
Buffy
Sissy
Keith
Danny
Lori
Chris
Shirley
Marsha
Jan
Cindy
Carol
Mike
Greg
Peter
Bobby
Alice
Ruben

Sample output

------------------------------------------------------------
12345678.123         size-1               
2short4me            size2                
mid_size_name        size3                
much_longer_name     tiny                 
shorter              very_long_file_name  
------------------------------------------------------------
Alfalfa        Cotton         Joe            Porky          
Buckwheat      Darla          Mrs_Crabapple  Stimey         
Butch          Froggy         P.D.           Weaser         
------------------------------------------------------------
Alice       Chris       Jan         Marsha      Ruben       
Bobby       Cindy       Jody        Mike        Shirley     
Buffy       Danny       Keith       Mr._French  Sissy       
Carol       Greg        Lori        Peter



#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;
}
int main()
{
    while(1){
        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());      //stl中的max,传入两个参数,返回最大值
            }
                               //计算列数cols和行数rows
            int cols=(maxcol-m)/(m+2)+1,rows=(n-1)/cols+1;
            print("",60,'-');           //调用函数,输出60个‘-’
            cout<<endl;
            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,' ');            //最后一列m个字符,其余m+2个字符
                }
                cout<<endl;
            }
        }
    }
    //system("pause");
    return 0;
}

 



posted @ 2016-03-08 17:36  Not-Bad  阅读(805)  评论(0编辑  收藏  举报