UVa 400 - Unix ls

本文介绍了一个使用C++实现的文件名排序及格式化打印程序。该程序能够读取一定数量的文件名,按字母顺序进行排序,并以美观的表格形式输出。通过计算每列的最大宽度和每行的最大项数来确保输出格式整齐。适用于需要批量处理文件并展示其列表的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
sort + printf格式控制
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cctype>
#include <cmath>
using namespace std;
const int MAXN = 104;
const int MAXL = 64;
char files[MAXN][MAXL];
int idx[MAXN];
int n, l;
int c, r;

bool cmp(int a, int b)
{
    return strcmp(files[a], files[b]) < 0;
}

void print()
{
    printf("------------------------------------------------------------\n");
    for(int i=0; i<r; i++) {
        for(int j=0; j<c; j++) {
            int k = j*r + i;
            if(k >= n) break;
            if(j<c-1) printf("%-*s", l+2, files[idx[k]]);
            else printf("%-*s", l, files[idx[k]]);
        }
        printf("\n");
    }
}

int main() {
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    #endif
    while(scanf("%d", &n)==1) {
        l = 1;
        for(int i=0; i<n; i++) {
            scanf("%s", files[i]);
            int t = strlen(files[i]);
            if(t > l) l = t;
            idx[i] = i;
        }
        c = (60-l)/(l+2) + 1;
        r = n%c ? n/c + 1 : n/c;
        sort(idx, idx+n, cmp);
        print();
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值