Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing int values with a user determined padding? [duplicate]

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!

like image 588
kanpeki Avatar asked Feb 17 '23 11:02

kanpeki


1 Answers

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().

like image 181
alk Avatar answered Mar 07 '23 11:03

alk