aboutsummaryrefslogtreecommitdiff
path: root/5.1.c
blob: 1301f6dc1dbc7259e9ca281a06b8cd95a49db272 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <ctype.h>

#define MAXBUFF 100

int getint(int *pn);
int getch(void);
void ungetch(int input);

int main(void)
{
        int input;

        getint(&input);
        printf("input: %d\n", input);

        return 0;
}

int getint(int *pn)
{
        char input, sign;

        while (isspace(input = getch()))
                ;

        if (!isdigit(input) && input != EOF && input != '+' && input != '-') {
                ungetch(input);
                return 0;
        }

        sign = (input == '-') ? -1 : 1;

        if (input == '-' || input == '+') {
                input = getch();

                if (!isdigit(input)) {
                        ungetch((sign == -1) ? '-' : '+');
                        return 0;
                }
        }

        for (*pn = 0; isdigit(input); input = getch())
                *pn = (*pn * 10) + (input - '0');

        *pn *= sign;

        if (input != EOF)
                ungetch(input);

        return input;
}

char buff[MAXBUFF];
int bpos = 0;

int getch(void)
{
        return (bpos) ? buff[--bpos] : getchar();
}

void ungetch(int input)
{
        if (bpos < MAXBUFF)
                buff[bpos++] = input;
        else
                printf("err: buff full\n");
}