/* * Program to get an integer from stdin without using scanf. * * (reading one character at a time and using recursion) * revised to skip leading whitespace and return error indicator */ #include #include #include #include int getint(bool *error); int main(void) { printf("enter a non-negative number\n"); bool err; int n = getint(&err); if (err) { printf("not a number\n"); return 1; } int next_ch = getchar(); if ((next_ch != ' ') && (next_ch != '\n')) { printf("not a number\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); } } /* * skip to first non-WS char and return it */ int skip_to_first_nonws(void) { int input = getchar(); if (!isspace(input)) return input; else return skip_to_first_nonws(); } /* * get an integer char by char from stdin, skipping any leading * whitespace and stopping when next char is not a digit * sets *error to true if first non-whitespace character not a digit, * else false */ int getint(bool *error) { int input = skip_to_first_nonws(); int first = char2digit(input); if (first == -1) { *error = true; return 0; } else { *error = false; return getint_r(first); } }