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;
}
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;
};
One potential issue is that s
is incremented by the outer loop before checking that it isn't pointing to the NULL terminator.
for(; *s != '\0'; s++)
{
...
for(; *s != '\0'; s++){
...
}
// inner loop is done now since we have *s=='\0' ...
...
// ... but now we're going to increment s again at the end of the outer loop!
}
You need to exit both the inner and outer loop immediately after the NULL terminator is spotted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With