做一个类似linux下的ls命令。列出文件名称,思路非常简单,就是排序。然后打印输出。打印的时候找对表达式来就OK了
不过我用C写了一个代码在codeblocks中运行没问题,在oj上提交就说runerror,具体原因我也没找出来。这里贴一下代码:
#include<stdio.h>
#include<stdlib.h>
char* a[102];
int sum;
int maxlong;
void sort(){
int i,j;
char* b;
for(i=0;i<sum;++i){
for(j=0;j<sum-i-1;++j){
if(a[j][0]>a[j+1][0]){
b = a[j];
a[j] = a[j+1];
a[j+1] = b;
}
}
}
}
int len(char *sp){
int i=0;
while(*sp!='\0'){
if(*sp != ' ')
++i;
sp++;
}
return i;
}
void gethome(){
int i;
for(i=0;i<102;++i){
a[i] = (char*)malloc(62*sizeof(char));
}
}
int main(){
gethome();
while(scanf("%d",&sum)==1){
int i,temp;
maxlong = 0;
for(i=0;i<sum;++i){
scanf("%s",a[i]);
temp=len(a[i]);
if (temp>maxlong)
maxlong = temp;
}
maxlong += 2;
sort();
int weith = 60/maxlong;
printf("------------------------------------------------------------\n");
int row=sum/weith;
if(row*weith<sum)
row+=1;
int j;
//printf("%d %d\n",row,weith);
for(i=0;i<row;++i){
for(j=0;j<weith;++j){
if(row*j+i>=sum)
continue;
printf("%-*s",maxlong,a[row*j+i]);
}
printf("\n");
}
}
}
这里值得一提的是关于打印可变的长度格式的字符串:
printf("%-*s",maxlong,a[row*j+i]);
这里的-表示向左对齐,没有-表示向右对齐。*对应着maxlong这个参数,表示占据的长度。如果对于浮点数保留小数位数可以用*.*,然后用两个参数分别对应。
printf("%*.*f",weith,long,float);
然后我再网上找了一份ac代码:
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
const int MAX = 128;
int cmp(const void*, const void*);
int main() {
char word[MAX][MAX];
int n, p, m;
int i, j, max, l, k;
while (cin >> n) {
max = 0;
for (i = 0; i < n; i++) {
cin >> word[i];
l = strlen(word[i]) + 2;
if (l > max)
max = l;
}
qsort(word, n, sizeof (word[0]), cmp);
if (max < 60)
p = 60 / max;
else
p = 1;
m = (n + p - 1) / p;
for (i = 0; i < 60; i++)
putchar('-');
putchar('\n');
for (i = 0; i < m; i++) {
for (j = 0, l = 0; j < p; j++) {
if (j * m + i < n) {
for (k = 0; k < l; k++)
putchar(' ');
l = max - strlen(word[j * m + i]);
cout << word[j * m + i];
}
}
putchar('\n');
}
}
return 0;
}
int cmp(const void *a, const void *b) {
if (strcmp((char*) a, (char*) b) < 0)
return -1;
else
return 1;
}
代码来源:https://blog.youkuaiyun.com/mylespower/article/details/6182558
其实整体思路都是差不多的,算是一道水题。