4

I'm pretty sure there's no way to do this, but I was wondering, so here goes...

Say I get several int values from the user, and I know for a fact that the 1st value is the largest. Any way I can use the length of the first int value as the padding when printing the rest of the numbers?

Browsing the forum I found that you can determine the length of an int (n) like this:

l = (int) log10(n) + 1;

Using padding of 5 a print would look like:

printf("%5d", n);

So what I want to know is whether or not there's a way to use l instead of 5...

Thank you!

alk
  • 69,737
  • 10
  • 105
  • 255
kanpeki
  • 435
  • 2
  • 6
  • 20

2 Answers2

8

Do it like so:

int n = <some value>;
int i = (int) log10(n) + 1;
printf("%*d", i, n);

The * serves as a placeholder for the width being passed as an argument to printf().

alk
  • 69,737
  • 10
  • 105
  • 255
0

You can use also snprintf() to get the number of characters printed for a value thus:

char buff[100];
int width = snprintf (buff, sizeof(buff), "%d", number1);

But, however you get the desired width, you can just use the * format modifier:

printf( "%*d %*d\n", width, number1, width, number2);

That modifier uses the next argument to specify a dynamic width rather than one fixed in the format string.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953