eminem92
eminem92

Reputation: 1

converting string to double in c

I am having a problem converting string to a double. Please help me out.

Here's my code:

char Price[100];
double newPrice;
printf("\nPlease enter the price:");
fgets(Price,100,stdin);
newPrice = atof  (Price);
printf("\nPrice of item is %f",newPrice);

It gives diff output while running with diff files.

file1 (method 1):

char   Price[100];
double newPrice;

int main()
{
    myval();
    return 0;
}

myval()
{
    printf("\nPlease enter the price:");
    fgets(Price, 100, stdin);

    newPrice = atof(Price);
    printf("\nPrice of item is %f", newPrice);  
}

file2 (method 2)

#define MAX 50

char    oldPrice[MAX];
double  newPrice;

int main()
{
    UserInput(); 
}

int UserInput()
{
    printf("\nPlease enter the price:");
    fgets(oldPrice, MAX, stdin);

    newPrice = atof(oldPrice);
    printf("\nPrice of item is %f", newPrice);  

    return 0;
}

The above two methods were compiled using tcc(tiny Compiler). Both methods are the same , but i get a diff output for these 2. output 1:

D:\>new.exe

Please enter the price:12.3

Price of item is 12.300000

Output 2:

D:\>t.exe

Please enter the price:12.3

Price of item is 7735248.000000

Upvotes: 0

Views: 165

Answers (2)

M Oehm
M Oehm

Reputation: 29116

You must include <stdlib.h> to get the right prototype for atof:

double atof(const char *);

With that, the behaviour is as expected. (I reckon that you included it for the first snippet, but not for the second.)

The compiler should warn you about using a function without prototype. Using a function without prototype is legal in C89, but the compiler will assume that the return value is int. That and printig the value with type-unaware printf seems to lead to the strange output.

In C99 and newer standards, it is illegal to use a function without prototype. So I recommend to use at least C99 if your compiler supports it. As a minimum, turn on compiler warnings.

Upvotes: 1

MrSykkox
MrSykkox

Reputation: 528

You are missing a include in your file.

#include < stdlib.h >

See also Converting char* to float or double

Upvotes: 0

Related Questions