In: Computer Science
Write a C function str_to_float() that takes a numeric string as
input and converts it to a floating
point number. The function should return the floating point number
by reference. If the
conversion is successful, the function should return 0, and -1
otherwise (e.g. the string does not
contain a valid number). The prototype of the function is given
below
int str_to_float(char * str, float * number);
Solution
#include <stdio.h>
int str_to_float(char * str, float
* number)
{
int i =0;
float f=0.0;
int res;
while(str[i]!='\0')
{
if(str[i]<48 || str[i]>57)
{
return -1;
}
int x= (int)str[i]-48; /* To get the digit from the character of
the string */
f = f*10 + x; /* f is the converted floating point number */
i++;
}
*number=f; /* number is a pointer to float so store f at the
address stored in number */
return 0;
}
int main()
{
char string[100];
float num=0.0;
int result;
printf("Enter a numeric string ");
scanf("%s", string);
result = str_to_float(string,&num);
if(result==-1)
{
printf("Entered string was not a valid numeric string");
}
if(result==0)
{
printf("The converted floating point number is %f",num);
}
return 0;
}
Explanation
The ASCII value of digits 0 to 9 is given below:
Digit | ASCII Value |
0 | 48 |
1 | 49 |
2 | 50 |
3 | 51 |
4 | 52 |
5 | 53 |
6 | 54 |
7 | 55 |
8 | 56 |
9 | 57 |
So we retrieve a character one by one from the string typecast it to integer(We get the ASCII value in this step). Next convert the ASCII value to numeric digit 0 to 9 by subtracting 48 from the ASCII value.
Screenshot
Output
Example of valid number
Example of invalid number