catofstrtod

Is there any difference in the way atof and strtod work?


I know that strtod() and atof() functions are used for conversion from string to double.

But I can't figure out the difference between these two functions.

Is there any difference between these two functions, if yes then please let me know...

Thanks in Advance.


Solution

  • From the man page on double atof(const char *nptr):

    The atof() function converts the initial portion of the string pointed to by nptr to double. The behavior is the same as

        strtod(nptr, NULL);
    

    except that atof() does not detect errors.

    Why can't it detect errors? Well, because that second argument of double strtod(const char *nptr, char **endptr) is used to point to the last character that couldn't be converted, so you can handle the situation accordingly. If the string has been successfully converted, endptr will point to \0. With atof, that's set to NULL, so there's no error handling.

    An example of error handling with strtod:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        const char *str = "1234.56";
        char *err_ptr;
        double d = strtod(str, &err_ptr);
        if (*err_ptr == '\0')
            printf("%lf\n", d);
        else
            puts("`str' is not a full number!");
    
        return 0;
    }