Skip to content

Commit e5c08ef

Browse files
committed
simplify answer
1 parent 5963868 commit e5c08ef

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

chapter04/4-9.c

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22
* Exercise 4-9. Our getch and ungetch do not handle a pushed-back EOF
33
* correctly. Decide what their properties ought to be if an EOF is pushed
44
* back, then implement your design.
5+
*
6+
* NOTE: the conversion of EOF (-1) from int to char and back to int may not
7+
* preserve negative value of EOF on some machines. Thus, we should declare buf[]
8+
* as int but[] to avoid conversion from from int to char to int of EOF.
9+
*
510
* Faisal Saadatmand
611
*/
712

@@ -16,24 +21,19 @@ void ungetch(int);
1621
void ungets(char []);
1722

1823
/* globals */
19-
char buf[BUFSIZE]; /* buffer from ungetch */
24+
int buf[BUFSIZE]; /* buffer from ungetch */
2025
int bufp; /* next free position in buf */
2126
int pushedEOF; /* signals EOF has been pushed-back */
2227

2328
/* getch: get a (possibly pushed back) character */
2429
int getch(void)
2530
{
26-
return (bufp > 0) ? buf[--bufp] : (pushedEOF) ? EOF : getchar();
31+
return (bufp > 0) ? buf[--bufp] : getchar();
2732
}
2833

2934
/* ungerch: push character back on input */
3035
void ungetch(int c)
3136
{
32-
if (c == EOF) {
33-
pushedEOF = 1;
34-
return;
35-
}
36-
3737
if (bufp >= BUFSIZE)
3838
printf("ungetch: too many characters\n");
3939
else
@@ -45,11 +45,11 @@ int main(void)
4545
{
4646
int c;
4747

48+
ungetch(EOF);
4849
ungetch('A');
4950
ungetch('B');
5051
ungetch('C');
5152
ungetch('D');
52-
ungetch(EOF);
5353

5454
while ((c = getch()) != EOF)
5555
putchar(c);

0 commit comments

Comments
 (0)