diff options
Diffstat (limited to '5.1.c')
-rw-r--r-- | 5.1.c | 90 |
1 files changed, 42 insertions, 48 deletions
@@ -1,74 +1,68 @@ #include <stdio.h> #include <ctype.h> -int getint(int *np); -char getch(void); -void ungetch(char input); +#define MAXBUFF 100 -int -main(void) -{ - int num; +int getint(int *pn); +int getch(void); +void ungetch(int input); - getint(&num); +int main(void) +{ + int input; - printf("%d\n", num); + getint(&input); + printf("input: %d\n", input); - return 0; + return 0; } -int -getint(int *np) +int getint(int *pn) { - int input, sign; + char input, sign; + + while (isspace(input = getch())) + ; - /* skip space */ - while (isspace(input = getch())) - ; + if (!isdigit(input) && input != EOF && input != '+' && input != '-') { + ungetch(input); + return 0; + } - if (!isdigit(input) && input != EOF && input != '+' && input != '-') { - ungetch(input); - return 0; - } + sign = (input == '-') ? -1 : 1; - sign = (input == '-') ? -1 : 1; + if (input == '-' || input == '+') { + input = getch(); - if (input == '+' || input == '-') - while (isspace(input = getch())) - ; + if (!isdigit(input)) { + ungetch((sign == -1) ? '-' : '+'); + return 0; + } + } - for (*np = 0; isdigit(input); input = getch()) - *np = *np * 10 + input - '0'; + for (*pn = 0; isdigit(input); input = getch()) + *pn = (*pn * 10) + (input - '0'); - *np *= sign; + *pn *= sign; - if (input != EOF) - ungetch(input); + if (input != EOF) + ungetch(input); - /* return last digit or EOF */ - return input; + return input; } -static char buff = -1; +char buff[MAXBUFF]; +int bpos = 0; -char -getch(void) +int getch(void) { - char temp; - - if (buff == -1) - return getchar(); - - temp = buff; - buff = -1; - return temp; + return (bpos) ? buff[--bpos] : getchar(); } -void -ungetch(char input) +void ungetch(int input) { - if (buff == -1) - buff = input; - else - printf("Err: buffer is full\n"); + if (bpos < MAXBUFF) + buff[bpos++] = input; + else + printf("err: buff full\n"); } |