-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.1.c
56 lines (51 loc) · 1.31 KB
/
5.1.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
53
54
55
56
/* Exercise 5-1. As written, getint treats a + or - not followed by a digit as
* a valid representation of zero. Fix it to push such a character back on the
* input.
*
* Each call sets array[n] to the next integer found in the input and increments
* n. Notice that it is essential to pass the address of array[n] to getint.
* Otherwise there is no way for getint to communicate the converted integer
* back to the caller.
*
* Our version of getint returns EOF for end of file, zero if the next input is
* not a number, and a positive value if the input contains a valid number.
*/
#include <stdio.h>
#include <ctype.h>
#include "lib/libkr.h"
#define SIZE 10
int getint(int *);
/* getint: get next integer from input into *pn */
int getint(int *pn)
{
int c, sign;
while (isspace(c = getch())) /* skip white space */
;
if (!isdigit(c) && c != EOF && c != '+' && c != '-') {
ungetch(c); /* it is not a number */
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '-' || c == '+') {
int buf = c;
if (!isdigit(c = getch())) {
ungetch(c);
ungetch(buf);
return 0;
}
}
for (*pn = 0; isdigit(c); c = getch())
*pn = 10 * *pn + (c - '0');
*pn *= sign;
if (c != EOF)
ungetch(c);
return c;
}
int
main(void)
{
int array[SIZE];
if ((getint(&array[0]) > 0))
printf("%d\n", array[0]);
return 0;
}