smooth_smoothie smooth_smoothie - 3 months ago 62
C Question

Converting string, to float (without atof) in C

I'm designing a function that will convert a string into a float.
e.g. "45.5" = 45.5

I have this so far. But it doesn't seem to work. Keep in mind, we cannot use any C library functions like atoi, atof or even pow for that matter.

int str2float( char *s )
{
int num = 0;
int dec = 0;
double i = 1.0;
int ten = 1;
/***** ADD YOUR CODE HERE *****/

for(; *s != '\0'; s++)
{
if (*s == '.'){
for(; *s != '\0'; s++){
dec = (dec * CONT) + (*s - '0');
i++;
}
}else{
num = (num * CONT) + (*s - '0');
}

}
for(;i!=0;i--){
ten *= 10;
}
dec = dec / (ten);
printf("%d", dec);
num += dec;
return num;
}

Answer

Here is my try:

float stof(const char* s){
  float rez = 0, fact = 1;
  if (*s == '-'){
    s++;
    fact = -1;
  };
  for (int point_seen = 0; *s; s++){
    if (*s == '.'){
      point_seen = 1; 
      continue;
    };
    int d = *s - '0';
    if (d >= 0 && d <= 9){
      if (point_seen) fact /= 10.0f;
      rez = rez * 10.0f + (float)d;
    };
  };
  return rez * fact;
};
Comments