From d31d5a09afd1720e1ff9562bef5b8fc03e312a13 Mon Sep 17 00:00:00 2001 From: sinanmohd Date: Sat, 5 Nov 2022 07:48:15 +0530 Subject: fix: 5.1, misunderstood question --- 5.1.c | 90 +++++++++++++++++++++++++++++++------------------------------------ 1 file changed, 42 insertions(+), 48 deletions(-) diff --git a/5.1.c b/5.1.c index a0e0559..1301f6d 100644 --- a/5.1.c +++ b/5.1.c @@ -1,74 +1,68 @@ #include #include -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"); } -- cgit v1.2.3