0

Hi. I have trouble with getting the following program to convert string to float type. What i need to do is this:

12.345e3 = 12345

12e-2=0.12

-12.34=-12.34

-12.34e3=-12340

-12.34e-2=-0.1234

e: = x 10^

I got it to do the basics. However, It doesn't work in case of negative numbers or exponents. While i completely understand it for exponents, i can't say the same for negative numbers. Also, I am pretty sure the code can be optimised. I just don't know how to do it.

```
#include <stdio.h>
#include <math.h>
#define SIZE 1024
int count(char S[SIZE],char c){
{
int i=0, count=0 ;
for( ; S[i] != 0 ; ++i )
if( S[i] == c ) ++count ;
return count ;
}}
float atof( char* s )
{
float num = 0.0;
float kon = 0.0;
int flag,flag2,i;
float exp;
while (*s) {
if (*s >= '0' && *s <= '9') {
num = 10.0 * num + (float)(*s - '0');
kon *= 10.0;
}
else if (*s == '.') kon = 1.0;
else if(*s == 'e'){
break;}
s++;
}
for(i=1;*(s+i);i++)
exp=exp*10+(*(s+i)-'0');
flag=count(s,'e');
if(flag!=0){
num = num / (kon == 0.0 ? 1.0 : kon);
num=num*pow(10,exp);}
else{
num = num / (kon == 0.0 ? 1.0 : kon);}
flag2=count(s,'-');
if(flag2!=0){
num=num*(-1);}
return num;
}
main()
{
float f;
char a[SIZE];
scanf( " %s", a );
f = atof(a);
printf( "atof(\"%s\")=%f\n", a, f );
}
```