3

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?

Mat
  • 202,337
  • 40
  • 393
  • 406
turnt
  • 3,235
  • 5
  • 23
  • 39
  • I think there's a new `alignas` keyword in the more recent language standard, but I'm unsure whether that was designed to solve this problem. (And maybe `_Alignas` is a variant that fills the gaps with underscores rather than spaces.) – Kerrek SB Jan 20 '13 at 01:50
  • 1
    @KerrekSB `alignas` has nothing to do with it, see [here](http://en.cppreference.com/w/cpp/language/alignas)... – t0mm13b Jan 20 '13 at 01:52
  • @t0mm13b Yes. I personally wouldn't care about the alignment, but I have to do so. – turnt Jan 20 '13 at 01:52
  • OP: Seen [this](http://stackoverflow.com/questions/757627/how-do-i-align-a-number-like-this-in-c?rq=1)? – t0mm13b Jan 20 '13 at 01:54
  • @KerrekSB what did you just say there - your comment was deleted *@t0mm13b: The meaning may have changed in C++. This question is about C, though.* You suggested *that*, and the question is clearly tagged as C! – t0mm13b Jan 20 '13 at 01:58

1 Answers1

8

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.

fge
  • 119,121
  • 33
  • 254
  • 329