How can variable field widths be implemented with printf ()?

The question arises:

How can I implement a variable field width with printf()? That is, instead of the %8dwidth should be indicated at run time.

I stumbled upon some C code on the Internet based on the above question, but since I'm new to C programming, I was unable to make heads or tails of code. I am posting the code below:

#include <stdio.h>

int main()
{
   const char text[] = "Hello world";
   int i;
   for ( i = 1; i < 12; ++i )
   {
      printf("\"%.*s\"\n", i, text);
   }


    return 0;
}
+4
source share
1 answer

First of all, let me tell you, the code you provided is for precision control, not field width. For short form **

 %A.B<format specifier>

Adenotes the width of the field and Bmakes precision.

, C11, Β§7.21.6.1, fprintf() ( )

%. %, :

[..]

  • , d, i, o, u, x x, , A, A, e, e, f f g g, , s. (.), asterisk * ( ) ; . , undefined.

, , , , . int . [...]

,

printf("\"%.*s\"\n", i, text);

i, .


( )

%
<Zero or more flags>
<optional minimum field width>
<optional precision>
<optional length modifier>
<A conversion specifier character>
+7

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


All Articles