/* * Program to get an integer from stdin without using scanf. * * (reading one character at a time and using recursion) */ #include #include int getint(void); int main(void) { printf("enter a non-negative number\n"); int n = getint(); int next_ch = getchar(); if ((next_ch != ' ') && (next_ch != '\n')) { printf("not an integer\n"); return 1; } printf("value is %d\n", n); return 0; } /* * for non-main functions, I just define them before first use rather * than having separate declarations and definitions */ /* * convert character to digit, returning -1 if character does not * represent a digit */ int char2digit (char c) { if ((c < '0') || (c > '9')) return -1; else return c - '0'; } /* * return integer that is 10 * previous_digits + rest of input */ int getint_r(int previous_digits) { int input = getchar(); int next = char2digit(input); if (next == -1) { ungetc(input, stdin); return previous_digits; } else { int temp = 10 * previous_digits + next; return getint_r(temp); } } /* * get an integer char by char from stdin, stopping when next char * is not a digit */ int getint(void) { int input = getchar(); int first = char2digit(input); if (first == -1) { /* * FIXME? this is ugly -- maybe think of some better way to * deal with errors? */ printf("not a number\n"); exit(1); } return getint_r(first); }