0

I'm learning C and I'm trying to extract a float value from a string, it must be in this kind of format. But when I enter a number in my string it only returns an int, can someone help me? thank you

#include <stdio.h>

float daNum(void);
int main (void)
{
  float value = 0;

printf("please enter a value:");
value =  daNum();

printf("your value is:%.3f \n", value);

return 0;
}


float daNum(void)
{
char store[121] = {0};    
float numba = 0;
int const kInvalInput = -5;

fgets (store, 121, stdin); 

if( sscanf (store, "%f", &numba) != 1)
{
numba = kInvalInput;
}

return numba;
}
JeanBook
  • 31
  • 7
  • works for me: https://ideone.com/i2yCbG – mch Mar 09 '20 at 13:01
  • 3
    What did you type as a value? Did you use dot or comma as the decimal point? – Jonathan Leffler Mar 09 '20 at 13:01
  • `3,14` is two integers separated by comma; `3.14` is a floating-point value (possibly depending on *locale*, but your program is using the "C" locale anyway). – pmg Mar 09 '20 at 13:04
  • @JonathanLeffler i used a dot – JeanBook Mar 09 '20 at 13:29
  • 1
    Using a dot is good, but it’s only part of what I asked. What did you type (and what did you get printed)? – Jonathan Leffler Mar 09 '20 at 13:34
  • Im testing it with visual studio and i get this please enter a value:1000.111111 your value is:1000.11108 (I edited the %.5f in the printf and added #pragma warning(disable: 4996) before the function definition) When i try to test it https://www.onlinegdb.com/online_c_compiler in this website i get a full int :/ @JonathanLeffler – JeanBook Mar 09 '20 at 13:54
  • 1
    @user3121023 its looks thats the answer to my problem but i havent seen pointers in class and i dont really understand it (ive tried) is this the only way to work around it? ty for your comment – JeanBook Mar 09 '20 at 13:59
  • 1
    Given that you’re using `float` rather than `double`, the `1000.11108` result is pretty much as good as can be expected. It isn’t an integer value. So I’m not clear what the problem is. It would also be a good idea to edit the “what I typed and what I got” information into the question. – Jonathan Leffler Mar 09 '20 at 14:01

1 Answers1

1

Use float strtof (const char* str, char** endptr);.

Full documentation

sephiroth
  • 896
  • 12
  • 22