-
ASCII to float
Hello again allmighty internet community: I'm a little bit stuck; I'm writting a program that will convert a number entered as a string into its correpsonding floating point representation. To do this I'm using the atof() function, which as I understan stands for ASCII to float. After watching the variables everything is ok except the converted variable which always gets an annoying 0.000000. Here's the code I've managed to cook so far:
Code:
#include<conio.h>
#include<stdio.h>
#include<string.h>
float Convert(char data[128]);
void main(void){
char data[128];
float result;
clrscr();
gets(data);
result=Convert(data);
clrscr();
printf("%f",result);
getch();
}
float Convert(char data[128]){
int i;
float max,res,power,value;
max=strlen(data);
res=0.0;
for (i=0;i<max;i++){
power=max-i-1;
value=power*atof(data[i]-'0');
res=res+value;
}
return res;
}
As I was saying power represents the 10^n value according to the decimal position, but for some reason atof(data[i]-'0') isn't working. Any ideas? Thank you.
-
You were close on atof() . atof() will take a string (char *) and convert to a double. If I say: atof("1.503"), I get a double set to 1.503. (It's in stdlib.h as well.)
You're feeding the function a plain old char... which could result in odd data/crashes. (Your compiler should've stopped you... but might've missed it since you didn't include the header.) Also, since it returns double, use double, they're more accurate than floats.
Edit: If I'm reading this right, I think atof() does exactly what you want Convert() to do. Do read the warning about atof() not returning errors in that man page as well.
-
Eureka
Cheers! I'm coding as we speak see if it works better.
-
atof converts a string to Float, you don't need to go character by character
just put res=atof(data);
I recommend first to check if all values are numbers or in case there is a point, that there's only one
-
Eureka
Cheers! Worked beautifuly.
-
Eureka
Cheers! Worked beautifuly.