Aligning Output Values in C

人盡茶涼 提交于 2021-01-21 10:12:35

问题


So I'm working on a program which needs to format output. The output is supposed to be aligned, and it does do so with small numbers:

This works

But then when I give big numbers, it no longer works:

This doesn't work

My code is really but here's the part that prints the main output:

/* 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);

How can I get the output to align?


回答1:


Use the available printf formatter capabilities:

$ 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  

As you can see, it even work with strings, so you can align your fields this way.



来源:https://stackoverflow.com/questions/14420924/aligning-output-values-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!