/* Puzzle S09 -- Convert a string to an int */ #include <stdio.h> #include <stdlib.h> int stringToInt( char *p ) { int value = 0; int multiplier = 1; /* change to -1 if string starts with minus */ if ( *p == '+' ) p++; if ( *p == '-' ) { multiplier = -1; p++ ; } while ( *p>='0' && *p<= '9' ) { value *= 10; value += *p - '0'; p++ ; } return value*multiplier; } int main(int argc, char *argv[]) { char *trials[] = { "1", "12", "+1", "-8", "+2003", "-345", "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]) ); } system("PAUSE"); return 0; }
Comments: