#include <stdio.h> #include <ctype.h> /*count digits, white space, others*/ int atoi(char[]); int main(void) { char ndigit[] = " -34"; printf("%d \n", atoi(ndigit)); return 0; } int atoi(char s[]) { int i=0, n, sign; for (i = 0; isspace(s[i]); i++) /* skip white space */ ; sign = (s[i] == '-') ? -1 : 1; if (s[i] == '+' || s[i] == '-') /* skip sign */ i++; for (n = 0; isdigit(s[i]); i++) n = 10 * n + (s[i] - '0'); return sign * n; } /*The C Programming Language (second edition, Prentice Hall) by Brian W. Kernighan and Dennis M. Ritchie*/
The structure of the program reflects the form of the input:
skip white space, if any
get sign, if any
get integer part and convert it
Each step does its part, and leaves things in a clean state for the next. The whole process terminates on the first character that could not be part of a number.
[The C Programming Language (second edition, Prentice Hall) by Brian W. Kernighan and Dennis M. Ritchie, p.61]