blob: a0e05593aaeaf6f31924b683d70b1308c11a146b (
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
69
70
71
72
73
74
|
#include <stdio.h>
#include <ctype.h>
int getint(int *np);
char getch(void);
void ungetch(char input);
int
main(void)
{
int num;
getint(&num);
printf("%d\n", num);
return 0;
}
int
getint(int *np)
{
int input, sign;
/* skip space */
while (isspace(input = getch()))
;
if (!isdigit(input) && input != EOF && input != '+' && input != '-') {
ungetch(input);
return 0;
}
sign = (input == '-') ? -1 : 1;
if (input == '+' || input == '-')
while (isspace(input = getch()))
;
for (*np = 0; isdigit(input); input = getch())
*np = *np * 10 + input - '0';
*np *= sign;
if (input != EOF)
ungetch(input);
/* return last digit or EOF */
return input;
}
static char buff = -1;
char
getch(void)
{
char temp;
if (buff == -1)
return getchar();
temp = buff;
buff = -1;
return temp;
}
void
ungetch(char input)
{
if (buff == -1)
buff = input;
else
printf("Err: buffer is full\n");
}
|