0

I am taking numerical string as an input from user and than converting it to float with the help of sscanf() function :

#include<stdio.h>

float getfloat(void);

int main()
{
    float a;
    a=getfloat();
    printf("You entered %f\n",a);
    return 0;
}

float getfloat(void)
{
    float n;
    char nstr[50];
    printf("Enter a numeric string\n");
    gets(nstr);
    sscanf(nstr,"%f",&n);
    return n;
}

Now let's suppose I enter a string 100.1234. After converting to float with help of sscanf when i print the float value i am getting 100.123398 as stored value. Now these are very close values but why am i not getting the same result as i entered. What is going on inside sscanf ?

anastaciu
  • 23,467
  • 7
  • 28
  • 53
LocalHost
  • 910
  • 3
  • 8
  • 24
  • 3
    The problem is not sscanf but floating point see [Is floating point math broken?](https://stackoverflow.com/q/588004/6865932) – anastaciu Aug 12 '20 at 17:33
  • 3
    I also suggest [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036/6865932) for `gets`. – anastaciu Aug 12 '20 at 17:35
  • As an alternative to `gets`, use [fgets()](https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm), i.e. `fgets(nstr, 50, stdin);` – ryyker Aug 12 '20 at 17:38
  • 1
    You won't get `100.123398` printed because your `getfloat()` returns `int`. – MikeCAT Aug 12 '20 at 17:45
  • sorry i forgot to edit this here. I meant float only. I have changed it appropriately. – LocalHost Aug 12 '20 at 17:47
  • @LocalHost, yes that's it, and to fix you problem, use `double` instead of `float`, don't forget the correct specifier `%lf`. – anastaciu Aug 12 '20 at 17:52

0 Answers0