3

所以我正在开发一个需要格式化输出的程序。输出应该是对齐的,并且它使用小数字这样做:

这有效

但是当我给出大数字时,它不再起作用:

这不起作用

我的代码确实是,但这是打印主要输出的部分:

/* The following code prints out the data */

    printf("\n\nStatistics: \n\n");
    printf("Descrip\t\tNumber:\t\tTotal:\t\tAverage:\n\n");
    printf("Normal\t\t%d\t\t%d\t\t%d\n\n",normal_counter,normal_total,normal_average);
    printf("Short\t\t%d\t\t%d\t\t%d\n\n",short_counter,short_total,short_average);
    printf("Long\t\t%d\t\t%d\t\t%d\n\n",long_counter,long_total,long_average);
    printf("Overall\t\t%d\t\t%d\t\t%d\n\n",overall_counter,overall_total,overall_average);

如何让输出对齐?

4

1 回答 1

8

使用可用的 printf 格式化程序功能:

$ cat t.c
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("%-12s%-12d%-12d\n", "a", 2989, 9283019);
    printf("%-12s%-12d%-12d\n", "helloworld", 0, 1828274198);
    exit(0);
}

$ gcc -Wall t.c
$ ./a.out 
a           2989        9283019     
helloworld  0           1828274198  

如您所见,它甚至可以使用字符串,因此您可以通过这种方式对齐字段。

于 2013-01-20T01:55:05.767 回答