C++ Notes: Solution - Convert C-string to double

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
// Convert C-string to double.
// Fred Swartz 2000

bool string2double(char* digit, double& result) {
   int sign = 1;

   result = 0;

   // check sign
   if (*digit == '-') {
      sign = -1;
      digit++;
   }

   //--- get integer portion
   while (*digit >= '0' && *digit <='9') {
      result = (result * 10) + *digit-'0';
      digit++;
   }

   //--- get decimal point and fraction, if any.
   if (*digit == '.') {
      digit++;
      double scale = 0.1;
      while (*digit >= '0' && *digit <='9') {
         result += (*digit-'0') * scale;
         scale *= 0.1;
         digit++;
      }
   }

   //--- error if we're not at the end of the number
   if (*digit != 0) {
      return false;
   }

   //--- set to sign given at the front
   result = result * sign;
   return true;
}