Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with usage of atof function?

Tags:

c

atof

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
like image 818
Naved Alam Avatar asked Feb 17 '13 05:02

Naved Alam


People also ask

What is the use of atof function?

The atof() function converts a character string to a double-precision floating-point value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.

How does atof work C++?

The atof() function ignores all the leading whitespace characters until the primary non-whitespace character is found. Then, beginning from this character, it takes as many characters as possible that forms a valid floating-point representation and converts them to a floating point value.

Where is atof defined?

Defined in header <stdlib.h> double atof( const char* str ); Interprets a floating-point value in a byte string pointed to by str . Function discards any whitespace characters (as determined by std::isspace()) until first non-whitespace character is found.


1 Answers

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.

like image 103
FatalError Avatar answered Sep 24 '22 15:09

FatalError