Puzzle S10

Convert a string of digits into a double

[H-20]Write function that accepts a string of digits and converts it into a double. For example the string "123.456" will be converted into the double value 123.456. Assume that the string might start with an optional plus or minus sign and that the the string is terminated by a null. There may be zero or one decimal point in the string. If one of the characters is not a digit (or a correctly possitioned plus, minus, or decimal point), stop the conversion and return whatever value has been calculated so far. Here is a prototype:

int stringToDouble( char *p );

Use Horner's method to calculate the integer part of the double. When the decimal point is encountered, start a divisor out at 10 and increase it by a factor of 10 for each new digit. Divide each digit past the decimal point by the current divisor and add the result to the current sum.

Here is a testing function:

/* Puzzle S10 --  string to double */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

double stringToDouble( char *p )
{
}

int main()
{
  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]) );
  }

   
  return 0;
}

The testing program compares the output of our stringToDouble() with the standard atof() which does the same thing. If the string starts with spaces, or there are spaces between the optional sign and the digits, then the conversion stops.

The standard atof()can convert strings that use scientific notation, as in the last test case above. Our function will fail with this. It would not be too hard to extend our function to deal with scientific notation.



Previous Page        Answer         Next Page         Home