What is wrong with usage of atof function?
Asked Answered
I

2

5
int main()
{
    char str[10]="3.5";
    printf("%lf",atof(str));
    return 0;
}

This is a simple code I am testing at ideone.com. I am getting the output as

-0.371627
Impost answered 17/2, 2013 at 5:11 Comment(2)
Possible duplicate.Paniagua
@AlexeyFrunze: Not at all. %lf is perfectly fine for printing a double.Overlive
E
17

You have not included stdlib.h. Add proper includes:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str[10]="3.5";
    printf("%lf",atof(str));
    return 0;
}

Without including stdlib.h, atof() is declare implicitly and the compiler assumes it returns an int.

Eternal answered 17/2, 2013 at 5:15 Comment(4)
OTOH, it looks like %lf is only proper in C99's printf() and not in C89's.Paniagua
Thanks, this was the error. Though I never heard of this before.Impost
Of what? Of the need to include headers or enable all warnings to see potential problems that the compiler can find?Paniagua
so this is the correct answer... but can someone explain why C is allowing me to call a function that does not exist?Narrowminded
M
0

It could be undefined behavior.

Molality answered 17/2, 2013 at 5:13 Comment(1)
no, %lf is the correct specifier for double, there's no issue with that. It's just that "If the converted value falls out of range of the return type, the return value is undefined" which is the same reason why atoi() shouldn't be usedActinism

© 2022 - 2024 — McMap. All rights reserved.