-
Notifications
You must be signed in to change notification settings - Fork 113
/
3.getint.c
52 lines (42 loc) · 793 Bytes
/
3.getint.c
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
#include <stdio.h>
#include <ctype.h>
#define SIZE 10
int getch(void);
void ungetch(int);
// compile with getch.c
int main()
{
int n, array[SIZE], getint(int *);
for (n = 0; n < SIZE; n++)
array[n] = 0;
for (n = 0; n < SIZE && getint(&array[n]) != EOF; n++)
;
for (n = 0; n < SIZE; n++)
printf("%d ", array[n]);
printf("\n");
return 0;
}
int getint(int *pn)
{
int c, sign;
while (isspace(c = getch()))
;
if (!isdigit(c) && c != EOF && c != '+' && c != '-') {
ungetch(c);
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-') {
c = getch();
if (!isdigit(c)) {
ungetch(sign == 1 ? '+' : '-');
return 0;
}
}
for (*pn = 0; isdigit(c); c = getch())
*pn = 10 * *pn + (c - '0');
*pn *= sign;
if (c != EOF)
ungetch(c);
return c;
}