How do I align a number like this in C?

后端 未结 11 729
清歌不尽
清歌不尽 2020-12-04 12:13

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

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

Of

11条回答
  •  臣服心动
    2020-12-04 13:15

    Looking at the edited question, you need to find the number of digits in the largest number to be presented, and then generate the printf() format using sprintf(), or using %*d with the number of digits being passed as an int for the * and then the value. Once you've got the biggest number (and you have to determine that in advance), you can determine the number of digits with an 'integer logarithm' algorithm (how many times can you divide by 10 before you get to zero), or by using snprintf() with the buffer length of zero, the format %d and null for the string; the return value tells you how many characters would have been formatted.

    If you don't know and cannot determine the maximum number ahead of its appearance, you are snookered - there is nothing you can do.

提交回复
热议问题