/* * program to get integer from input, maybe more nicely than scanf * * version from 9/26 class */ #include int getint(int *result_p); char first_non_blank(); int collect_digits(char first, int previous, int *result_p); int char_to_digit(char c); int main(void) { int result; printf("enter an integer\n"); if (getint(&result) == 0) { printf("%d\n", result); } else { printf("error\n"); } return 0; } /* * get integer from stdin * returns 0 on success, something else on error */ int getint(int *result_p) { /* skip over leading blanks */ char first = first_non_blank(); int sign = 1; /* negative */ if (first == '-') { sign = -1; first = getchar(); } /* first nonblank is not a digit */ else if (first < '0' || first > '9') { return 1; } /* first nonblank is a digit */ int status = collect_digits(first, 0, result_p); if (status == 0) { *result_p *= sign; } return status; } /* * get first nonblank from stdin */ char first_non_blank() { char ch = getchar(); if (ch != ' ') { return ch; } else { return first_non_blank(); } } /* * collect digits and turn into integer * assumes first character is not blank * "first" is a digit * "previous" is the digits to the left, as an int * returns 0 on success, something else on error * * FIXME sometime? this seems kind of ugly */ int collect_digits(char first, int previous, int *result_p) { char next = getchar(); if (next == ' ' || next == '\n') { *result_p = 10*previous + char_to_digit(first); return 0; } else if ((next < '0') || (next > '9')) { return 1; } else { return collect_digits(next, 10*previous + char_to_digit(first), result_p); } } int char_to_digit(char c) { return c-'0'; }