/* * Program to get an integer from stdin without using scanf. * * (reading one character at a time and using a loop) */ #include #include #include #include /* * get an integer char by char from stdin, stopping when next char * not a digit, and skipping leading white space (spaces, newlines, etc.) * *bool will be true if no integer found, false otherwise */ int getint(bool *error); int main(void) { printf("enter a non-negative number\n"); bool err; int n = getint(&err); if (err) { printf("not an integer\n"); return 1; } 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'; } /* * get an integer char by char from stdin, skipping leading ws, * stopping when next char * and set *err to true if no digits */ int getint(bool *error) { *error = false; /* read input until a non-whitespace is found */ int input; input = getchar(); while (isspace(input)) { input = getchar(); } /* input is first non-space */ /* check whether first non-space is a digit */ int first = char2digit(input); if (first == -1) { *error = true; return 0; } /* now read and accumulate digits until non-digit found */ int to_return = first; do { input = getchar(); first = char2digit(input); if (first != -1) { to_return = to_return * 10 + first; } } while (first != -1); /* put character back in stdin for caller */ ungetc(input, stdin); return to_return; }