Skip to content

Commit b1a364f

Browse files
committed
improve answer
1 parent bda77ac commit b1a364f

File tree

1 file changed

+16
-21
lines changed

1 file changed

+16
-21
lines changed

Diff for: chapter04/4-8.c

+16-21
Original file line numberDiff line numberDiff line change
@@ -2,53 +2,48 @@
22
* Exercise 4-8. Suppose that there will never be more than one character of
33
* pushback. Modify getch and ungetch accordingly.
44
*
5-
* NOTE: see alternate version 4-8a.c
6-
*
75
* Faisal Saadatmand
86
*/
97

108
#include <stdio.h>
11-
#include <stddef.h> /* for NULL */
129

1310
/* functions */
1411
int getch(void);
1512
void ungetch(int);
1613

1714
/* globals */
18-
char buf; /* buffer from ungetch */
19-
char *bufp = NULL; /* pointer to buf */
15+
int buf; /* buffer from ungetch */
2016

2117
/* getch: get a (possibly pushed back) character */
2218
int getch(void)
2319
{
24-
char temp;
25-
26-
if (bufp) {
27-
temp = *bufp;
28-
bufp = NULL;
29-
return temp;
30-
}
31-
return getchar();
20+
int c;
21+
22+
if (buf) {
23+
c = buf;
24+
} else
25+
c = getchar();
26+
buf = 0;
27+
return c;
3228
}
3329

3430
/* ungerch: push character back on input */
3531
void ungetch(int c)
3632
{
37-
if (!bufp)
38-
bufp = &buf; /* initialize buffer pointer */
39-
*bufp = c;
33+
if (buf)
34+
printf("ungetch: too many characters\n");
35+
else
36+
buf = c;
4037
}
4138

4239
/* test getch */
4340
int main(void)
4441
{
4542
ungetch('A');
46-
ungetch('B');
43+
ungetch('B'); /* should give error */
44+
printf ("%c\n", getch());
4745
ungetch('C');
48-
ungetch('D');
49-
50-
putchar(getch());
51-
printf ("\n");
46+
printf ("%c\n", getch());
5247

5348
return 0;
5449
}

0 commit comments

Comments
 (0)