Microsoft KB Archive/47663

= Microsoft Knowledge Base =

Variable Width, Precision Available with printf
Last reviewed: July 22, 1997

Article ID: Q47663

5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a | 1.00 1.50 | 1.00 2.00 4.00

MS-DOS                     | OS/2            | WINDOWS   | WINDOWS NT kbprg kbcode kbfasttip

The information in this article applies to:

The C Run-time (CRT), included with:

- Microsoft C for MS-DOS, versions 5.1, 6.0, 6.0a, and 6.0ax - Microsoft C for OS/2, versions 5.1, 6.0, and 6.0a - Microsoft C/C++ for MS-DOS, version 7.0 - Microsoft Visual C++ for Windows, versions 1.0 and 1.5 - Microsoft Visual C++ 32-bit Edition, versions 1.0, 2.0, and 4.0 The Microsoft C Run-time library function printf allows the width of the format specifier to be supplied at run time. This is done with the use of the * with the format specifier. The following code sample demonstrates this capability.

Sample Code
/* This program defines a procedure to print out a floating-point number with variable width and precision.

/* Compile options needed: none


 * 1) include 

void print(int, int, float);

void main(void) { print (10, 2, 1234.5678f); print (9, 4, 1234.5678f); print (5, 2, 1234.5678f); }

void print(int w, int p, float value) { printf (&quot;Printf format :%*.*f\n&quot;, w, p, value); printf (&quot;Width =       0123456789012\n&quot;); }