0

According to https://cplusplus.com/reference/cstdio/printf/ the printf format specifier follows this prototype:

%[flags][width][.precision][length]specifier  

Regarding width the above-mentioned web page states:

Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.

In the sample source code, as shown below, I have specified a width of 4 and a precision of 2, for printing the value of PI. I was expecting the output to be padded by a single blank space, to meet the field width constraint of 4, since the precision is 2. However, I am finding that the output is not padded by a single blank space.

#include <stdio.h>
#include <math.h>

int main()
{
   printf ("PI:%4.2f\n", M_PI);
   // Outputs PI:3.14, and not
   // PI: 3.14
   
   return 0;
}
Sandeep
  • 1,245
  • 1
  • 13
  • 33

1 Answers1

0

Minimum number of characters to be printed

3.14 was printed - that's 4 characters 3 . 1 4. If you want to print an additional space, that would be 5 characters 3 . 1 4 - so width 5.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111