Encoders
Hub for Computer Whizzes Register to join us

Encoders > More... > C > Program

/* Function atof(s) that converts a string into floating point number after
   skipping the white spaces in the beginning and terminating the conversion
   when the first non-digit character is encountered. */

#include <stdio.h>

double atof(char s[]);

main()
{
	char a[100];
	double i;
	gets(a);
        printf("%f\n",atof(a));
}

double atof(char s[])
{
	double n, power;
	int i, sign=1;
	for(i=0; s[i]==' ' || s[i]=='\t' || s[i]=='\n'; i++)
		;
	if(s[i]=='-' || s[i]=='+')
		sign = s[i++]=='-'?-1:1;
       	for(n=0; s[i]>='0'&&s[i]<='9'; i++)
		n = n*10 + s[i]-'0';

	if(s[i]=='.')
		i++;
        for(power=1;s[i]>='0'&&s[i]<='9';i++)
	{
		n=n*10 + s[i]-'0';
		power *= 10;
	}
	return sign*n/power;
}