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.
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.