In: Computer Science
#include<stdio.h>
float stofloat(char *);
int main() {
char ch[20];// take maximum 19 length string
float i;
printf("\n enter the number as a string\n");
scanf("%[^\n]", ch);//*take a string with digit like float
value
i = stofloat(ch); // in this function passing base address of the
string
printf(" string =%s , float =%g \n", ch, i); // print orginal
string and converted float value
return 0;
}
float stofloat(char *p) // p is a pointer which holds base address of ch string and return float value
{
// take two variables for counting the number of digits in
mantissa
int i, num = 0, num2 = 0, pnt= 0, x = 0, y = 1;
float f1, f2, f3;
for (i = 0; p[i]; i++) //this loop will continue up to decimal
point
if (p[i] == '.') {
pnt = i;
break;
}
for (i = 0; p[i]; i++) // this loop will cotnue up to end of the
string
{
if (i < pnt)
num = num * 10 + (p[i] - 48);
else if (i == pnt)
continue;
else {
num2 = num2 * 10 + (p[i] - 48);
++x;
}
}
// it takes 10 if it has 1 digit ,100 if it has 2 digits in
mantissa
for (i = 1; i <= x; i++)
y = y * 10;
f2 = num2 / (float) y;
f3 = num + f2;
return f3;
}
output1:
enter the number as a string
005.549
string =005.549 , float =5.549
output2:
enter the number as a string
3.34
string =3.34 , float =3.34