1

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.

Abhishek Jaiswal
  • 288
  • 2
  • 14
  • For one thing, they take different arguments. Did you look at the man page for each of them? Are you able to see that the arguments are different? The answer is "yes", the two functions are different. – Tom Karzes May 02 '21 at 07:22
  • @TomKarzes I know that difference(number of arguments), I want to know other differences. – Abhishek Jaiswal May 02 '21 at 07:29
  • Then that's what you should have asked. What you actually asked was "Is there any difference between these two functions, if yes then please let me know..." I did just that. There is nothing in your post that suggests you were aware of *any* differences between the two functions. – Tom Karzes May 02 '21 at 07:31
  • @TomKarzes Okay I apologize. – Abhishek Jaiswal May 02 '21 at 07:34
  • @AbhishekJaiswal consider rephrasing your question to make it a bit more clear. Like for example change your title to something like "Is there any difference in the way atof and strtod work?" – mediocrevegetable1 May 02 '21 at 07:37
  • same as the difference between [`atol()`](https://en.cppreference.com/w/cpp/string/byte/atoi) and [`strtol()`](https://en.cppreference.com/w/c/string/byte/strtol): the `ato*()` family has undefined behavior and `strto*()` doesn't. See [Why shouldn't I use `atoi()`?](https://stackoverflow.com/q/17710018/995714) – phuclv May 02 '21 at 14:33

1 Answers1

3

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;
}
mediocrevegetable1
  • 4,086
  • 1
  • 11
  • 33