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

后端 未结 1 1743
我在风中等你
我在风中等你 2020-12-21 00:44

The question is :

How can variable field width be implemented using printf()? That is, instead of %8d, the width should be s

相关标签:
1条回答
  • 2020-12-21 01:13

    First of all, let me tell you, the code you have shown is about controlling the precision, not the field width. For a shortened form**

     %A.B<format specifier>
    

    A denotes the field width and B makes the precision.

    Now, quoting the C11 standard, chapter §7.21.6.1, fprintf() (emphasis mine)

    Each conversion specification is introduced by the character %. After the %, the following appear in sequence:

    [..]

    • An optional precision that gives the minimum number of digits to appear for the d, i, o, u, x, and X conversions, the number of digits to appear after the decimal-point character for a, A, e, E, f, and F conversions, the maximum number of significant digits for the g and G conversions, or the maximum number of bytes to be written for s conversions. The precision takes the form of a period (.) followed either by an asterisk * (described later) or by an optional decimal integer; if only the period is specified, the precision is taken as zero. If a precision appears with any other conversion specifier, the behavior is undefined.

    and

    As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an int argument supplies the field width or precision. [...]

    So, in your case,

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

    the precision will be supplied by i which can hold different values at run-time.


    The complete format (broken down in separate lines for ease of readability)

    %
    <Zero or more flags>
    <optional minimum field width>
    <optional precision>
    <optional length modifier>
    <A conversion specifier character>
    
    0 讨论(0)
提交回复
热议问题