Printing int values ​​with custom padding?

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

Let's say I get some int values ​​from the user, and I know that the 1st value is the largest. In any case, can I use the length of the first int value as a complement when printing the remaining numbers?

Looking through the forum, I found that you can determine the length of int (n), like this:

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

Using indentation 5, the print will look like this:

 printf("%5d", n); 

So I want to know if there is a way to use l instead of 5 ...

Thanks!

+4
source share
2 answers

Do it like this:

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

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

+8
source

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

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

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

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

This modifier uses the following argument to specify a dynamic width, rather than one fixed in a format string.

0
source

Source: https://habr.com/ru/post/1481888/


All Articles