Puzzle S9

Convert a string of digits into an integer

[H-12]Write function that accepts a string of digits and computes the corresponding int. For example the string "123" will be converted into the int value 123. (Usually this is called "converting the string into an integer," although the string itself is not actually changed.) Assume that the string might start with an optional plus or minus sign and that the the string is terminated by a null. If one of the characters is not a digit, stop the conversion and return whatever value has been calculated so far. Here is a prototype:

int stringToInt( char *p );

Use Horner's method to calculate the int:

value = 0
start with leftmost digit
while digit is '0' through '9' 
  value = value * 10
  value = value + integer equivalent of digit
  move to next digit
  
return value  

You can write the function using entierly your own code, or use the standard functions isdigit() and toint() from <ctype.h> . Here is a testing function:

/* Puzzle S09 --  string to int */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int stringToInt( char *p )
{
}

int main()
{
  char *trials[] =
  {
   "1",
   "12",
   "+1",
   "-8",
   "+2003",
   "-345",
   "9876  ",
   "12o5",
   "rats",
   "--oh dear--",
   "+ 234",
   "++45"
  };

  int j ;
  for ( j=0; j<sizeof(trials)/sizeof(char *); j++ )
  {
    printf("%s is converted into: %d\t\tshould be: %d\n", trials[j],
         stringToInt( trials[j]), atoi( trials[j]) );
  }

   
  return 0;
}

The testing program compares the output of our stringToInt() with the standard atoi() 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.



Previous Page        Answer         Next Page         Home