Skip to content

Commit 06e4990

Browse files
committed
revise answer
1 parent 9126085 commit 06e4990

File tree

1 file changed

+13
-24
lines changed

1 file changed

+13
-24
lines changed

chapter05/5-1.c

Lines changed: 13 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,14 @@
1010
#include <ctype.h>
1111

1212
#define BUFSIZE 100
13-
#define SIZE 100
1413

1514
/* functions */
1615
int getch(void);
1716
void ungetch(int);
1817
int getint(int *);
1918

2019
/* global */
21-
int buf[BUFSIZE]; /* buffer from ungetch */
20+
int buf[BUFSIZE]; /* buffer from ungetch (can handle EOF push back) */
2221
int bufp = 0; /* next free position in buf */
2322

2423
int getch(void) /* get a (possibly pushed back) character */
@@ -37,40 +36,30 @@ void ungetch(int c) /* push character back on input */
3736
/* getint: get next integer from input into *pn */
3837
int getint(int *pn)
3938
{
40-
int c, sign, signChar;
39+
int c, sign;
4140

42-
while (isspace(c = getch())) /* skip white space */
41+
while (isspace(c = getch())) /* skip white space */
4342
;
44-
if (!isdigit(c) && c != EOF && c != '+' && c != '-')
45-
return 0; /* it is not a number */
46-
sign = (c == '-') ? -1 : 1;
47-
if (c == '+' || c == '-') {
48-
signChar = c;
49-
if (!isdigit(c = getch())) {
50-
if (c != EOF)
51-
ungetch(c);
52-
ungetch(signChar);
53-
return signChar;
54-
}
43+
if (!isdigit(c) && c != '+' && c != '-') {
44+
ungetch(c); /* it is not a number */
45+
return 0;
5546
}
47+
sign = (c == '-') ? -1 : 1;
48+
if (c == '+' || c == '-')
49+
if (!isdigit((c = getch()))) /* sign followed by a digit? */
50+
return 0; /* not a number */
5651
for (*pn = 0; isdigit(c); c = getch())
5752
*pn = 10 * *pn + (c - '0');
5853
*pn *= sign;
59-
if (c != EOF)
6054
ungetch(c);
6155
return c;
6256
}
6357

6458
int main(void)
6559
{
66-
int array[SIZE], input;
67-
size_t n;
60+
int input, num;
6861

69-
for (n = 0; n < SIZE && (input = getint(&array[n])) != EOF; ++n) {
70-
if (input == 0 || input == '-' || input == '+')
71-
break;
72-
printf(" %i", array[n]);
73-
}
74-
printf("\n");
62+
while ((input = getint(&num)) && input != EOF)
63+
printf("%i\n", num);
7564
return 0;
7665
}

0 commit comments

Comments
 (0)