J Mei J Mei - 5 months ago 50
C Question

How to format printf output

I have a for loop that prints out data from an array but I want them to print out so that they all line up neatly.

1. 123124124 24
2. 12412452 56
3. 12312 12
10. 12412412 12

I have
printf("%d.%d%d\n", x, y, z)
; Any help is appreciated!

printf("%-3d%-12d%d\n", x, y, z);

The number following the minus sign and preceeding the d is the minimum width of the field. For the count column, we want it to be at least 3 columns wide. However, we also want it to pad to the right, which is why the minus sign is used.

Same goes for the %-12d, except that the minimum width is 12. Have a look at this sample


If you want the period, you're going to have to print that as a string with %s.