Alex Rivera | Logout

How do I align a number like this in C?

Asked 2009-04-16T19:16:36.913
43

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.

Edit
Report

2 Answers

59

Looking this up in my handy Harbison & Steele....

Determine the maximum width of fields.

int max_width, value_to_print;
max_width = 8;
value_to_print = 1000;
printf("%*d\n", max_width, value_to_print);

Bear in mind that max_width must be of type int to work with the asterisk, and you'll have to calculate it based on how much space you're going to want to have. In your case, you'll have to calculate the maximum width of the largest number, and add 4.

answered 2009-04-16T20:14:47.757
1

Try converting to a string and then use "%4.4s" as the format specifier. This makes it a fixed width format.

answered 2009-04-16T21:43:43.657

Your Answer