/* * program to get integer from input, maybe more nicely than scanf * * version using loops */ #include int getint(int *result_p); char first_non_blank(); int collect_digits(char first, 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, result_p); if (status == 0) { *result_p *= sign; } return status; } /* * get first nonblank from stdin */ char first_non_blank() { /* simple way char ch = getchar(); while (ch == ' ') { ch = getchar(); } */ /* shorter way */ char ch; while ((ch = getchar()) == ' ') { } return ch; } /* * collect digits and turn into integer * "first" is a digit * returns 0 on success, something else on error */ int collect_digits(char first, int *result_p) { int work = char_to_digit(first); /* get digits while more to get */ /* straightforward way */ char next = getchar(); while ((next >= '0') && (next <= '9')) { work = 10*work + char_to_digit(next); next = getchar(); } /* shorter but less readable(?) way */ /* char next; while ((next = getchar()) && (next >= '0') && (next <= '9')) { work = 10*work + char_to_digit(next); } */ /* at exit from the loop, "next" has a non-digit */ if ((next == ' ') || (next == '\n')) { *result_p = work; return 0; } else { return 1; } } int char_to_digit(char c) { return c-'0'; }