#include <stdio.h> #include <stdlib.h> double stringToDouble( char *p ) { double intPart=0.0, fractionPart=0.0; int multiplier = 1; /* change to -1 if string starts with minus */ /* Find the sign for the entire number */ if ( *p == '+' ) p++; if ( *p == '-' ) { multiplier = -1; p++ ; } /* Convert the integer part of the number */ while ( *p >= '0' && *p <= '9' ) { intPart *= 10; intPart += *p - '0'; p++ ; } /* Convert the fractional part of the number */ if ( *p == '.' ) { double divisor = 1.0; p++ ; while ( *p >= '0' && *p <= '9' ) { divisor *= 10.0; fractionPart += (*p - '0')/divisor; p++ ; } } /* Put the pieces together */ return (intPart + fractionPart)*multiplier ; } int main(int argc, char *argv[]) { char *trials[] = { "1", "1.2", "+1", "-8.000", "+2003.99", "-3.45", "98.76 ", "12..5", "rats", "+95.M", "+ 234", ".999", "+1.345E+005" /* Our function will not work for this */ }; int j ; for ( j=0; j<sizeof(trials)/sizeof(char *); j++ ) { printf("%s is converted into: %lf\t\tshould be: %lf\n", trials[j], stringToDouble( trials[j]), atof( trials[j]) ); } system("PAUSE"); return 0; }
Comments: