How do I align a number like this in C?

rfgamaral picture rfgamaral · Apr 16, 2009 · Viewed 137k times · Source

I need to align a series of numbers in C with printf() like this example:

-------1
-------5
------50
-----100
----1000

Of course, there are numbers between all those but it's not relevant for the issue at hand... Oh, consider the dashes as spaces, I used dashes so it was easier to understand what I want.

I'm only able to do this:

----1---
----5---
----50--
----100-
----1000

Or this:

---1
---5
--50
-100
1000

But none of this is what I want and I can't achieve what is displayed on the first example using only printf(). Is it possible at all?

EDIT:
Sorry people, I was in a hurry and didn't explain myself well... My last example and all your suggestions (to use something like "%8d") do not work because, although the last number is 1000 it doesn't necessarily go all the way to 1000 or even 100 or 10 for that matter.

No matter the number of digits to be displayed, I only want 4 leading spaces at most for the largest number. Let's say I have to display digits from 1 to 1000 (A) and 1 to 100 (B) and I use, for both, "%4d", this would be the output:

A:

---1
....
1000

Which is the output I want...

B:

---1
....
-100

Which is not the output I want, I actually want this:

--1
...
100

But like I said, I don't know the exact number of numbers I have to print, it can have 1 digit, it can have 2, 3 or more, the function should be prepared for all. And I want four extra additional leading spaces but that's not that relevant.

EDIT 2: It seems that what I want, the way I need it, it's not possible (check David Thornley and Blank Xavier answers and my comments). Thank you all for your time.

Answer

dwc picture dwc · Apr 16, 2009

Why is printf("%8d\n", intval); not working for you? It should...

You did not show the format strings for any of your "not working" examples, so I'm not sure what else to tell you.

#include <stdio.h>

int
main(void)
{
        int i;
        for (i = 1; i <= 10000; i*=10) {
                printf("[%8d]\n", i);
        }
        return (0);
}

$ ./printftest
[       1]
[      10]
[     100]
[    1000]
[   10000]

EDIT: response to clarification of question:

#include <math.h>
int maxval = 1000;
int width = round(1+log(maxval)/log(10));
...
printf("%*d\n", width, intval);

The width calculation computes log base 10 + 1, which gives the number of digits. The fancy * allows you to use the variable for a value in the format string.

You still have to know the maximum for any given run, but there's no way around that in any language or pencil & paper.