Maximum field width of scanf() with float

Viewed 428

The maximum field width specified in the control string in the scanf() function specifies the maximum number of characters that can be read into the variable.

According to this explanation, if the input for the following code is 123.456, the output should be 123.45, but I am getting 123.4 as the output.

#include <stdio.h>

int main() {
    float f;
    scanf("%5f", &f);
    printf("%f", f);

    return 0;
}

I am unable to understand the reason for the output.

2 Answers

According to this explanation,
if the input for the following code is 123.456, the output should be 123.45 but I am getting 123.4 as the output.

Yes, you are getting the right output as per the code you have written.

The "%5f" you used in scanf, specifies the maximum number of characters to be read in the current reading operation.

so in your output, 123.4 are 5 characters( including the .)

If you want to print x number of digits after ., use %.xf

#include <stdio.h>
    
int main() {
    float f;
    printf("Enter a float number:");
    scanf("%f", &f);
    printf(" with .2f = %.2f\n", f);
    printf(" default  = %f\n", f);
    
    return 0;
}

output:

Enter a float number:123.456
 with .2f = 123.46
 default  = 123.456001

The maximum field width specified in the control string in the scanf() function specifies the maximum number of characters that can be read into the variable.

Not quite.

With scanf("%5f", &f);, the "%5f" directs scanf() to first read and discard leading white-spaces. These white-spaces do not count toward the 5.

Then up to 5 numeric characters are read. These include 0-9, - +, e, E, NAN, nan, inf...

  12345
 "123.45"     --> "123.4" is read, "5" remains in stdin
 "-123.45"    --> "-123." is read, "45" remains in stdin
 "+123.45"    --> "+123." is read, "45" remains in stdin
 "000123.45"  --> "00012" is read, "3.45" remains in stdin
 "1.2e34"     --> "1.2e3" is read, "4" remains in stdin
 "123x45"     --> "123" is read, "x45" remains in stdin
 " 123.45"    --> " 123.4" is read, "5" remains in stdin

Using a width limit with "%f" in scanf() can be problematic. Consider setting aside scanf() and use fgets() to read user input into a string and then parse the string.

Related