Task 1: Convert a number string to number 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);
#include<stdio.h>
#include<stdlib.h>
int str_to_float(char* str, float* number){
*number= atof(str);
if(*number==0)
return -1;
else
return 0;
}
void main(){
char s[200];
float number=0;
int k;
printf("Enter your string ");
scanf("%[^\n]%*c", s);
k=str_to_float(s,&number);
if(k==0){
printf("convert successfully\n");
printf("%f",number);
}
else
printf("not converted\n");
}
Comments
Leave a comment