1

I need to convert a string into a float. If the string is not a number I wish to return 0.

I have tried to test if the atof() function would work for this by using the following code:

printf("%f", atof("1a"));

From my understanding of atof, the value returned when atof cannot convert is 0, and yet this line prints 1.0.

Why does this happen? By the documentation I understood that atof is meant to return 0 whenever the input is not a number.

Random Davis
  • 6,662
  • 4
  • 14
  • 24
JinKazama
  • 81
  • 3
  • 15
  • you might be better off using: `strtod()`. Do note that `atof()` actually returns a `double`, not a `float`. Note: the function: `atof()` will see the `1` as a valid number and return the result of the conversion: 1.000000. There is no reason for it to return 0.000000 as there is a valid number to convert. – user3629249 May 20 '16 at 22:57

3 Answers3

3

From doc. Emphasis mine

The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax resembling that of floating point literals (see below), and interprets them as a numerical value. The rest of the string after the last valid character is ignored and has no effect on the behavior of this function.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
1

I saw that you checked some documentation, but you must have missed the emphasized part - it's important to make sure you read documentation thoroughly: http://www.cplusplus.com/reference/cstdlib/atof/

The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax resembling that of floating point literals (see below), and interprets them as a numerical value. The rest of the string after the last valid character is ignored and has no effect on the behavior of this function.

Thus, the function is behaving exactly as it should - the a character in "1a" is being ignored.

Random Davis
  • 6,662
  • 4
  • 14
  • 24
1

yet this line prints 1.0.

printf("%f", atof("1a"));

worked because atof could parse atleast one number ie 1 in this case.

But:

char a[]="a1";
printf("%f\n",atof(a));

should have given you a return value of 0.0 as you expected.

sjsam
  • 21,411
  • 5
  • 55
  • 102