File tree Expand file tree Collapse file tree 1 file changed +8
-8
lines changed Expand file tree Collapse file tree 1 file changed +8
-8
lines changed Original file line number Diff line number Diff line change 2
2
* Exercise 4-9. Our getch and ungetch do not handle a pushed-back EOF
3
3
* correctly. Decide what their properties ought to be if an EOF is pushed
4
4
* 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
+ *
5
10
* Faisal Saadatmand
6
11
*/
7
12
@@ -16,24 +21,19 @@ void ungetch(int);
16
21
void ungets (char []);
17
22
18
23
/* globals */
19
- char buf [BUFSIZE ]; /* buffer from ungetch */
24
+ int buf [BUFSIZE ]; /* buffer from ungetch */
20
25
int bufp ; /* next free position in buf */
21
26
int pushedEOF ; /* signals EOF has been pushed-back */
22
27
23
28
/* getch: get a (possibly pushed back) character */
24
29
int getch (void )
25
30
{
26
- return (bufp > 0 ) ? buf [-- bufp ] : ( pushedEOF ) ? EOF : getchar ();
31
+ return (bufp > 0 ) ? buf [-- bufp ] : getchar ();
27
32
}
28
33
29
34
/* ungerch: push character back on input */
30
35
void ungetch (int c )
31
36
{
32
- if (c == EOF ) {
33
- pushedEOF = 1 ;
34
- return ;
35
- }
36
-
37
37
if (bufp >= BUFSIZE )
38
38
printf ("ungetch: too many characters\n" );
39
39
else
@@ -45,11 +45,11 @@ int main(void)
45
45
{
46
46
int c ;
47
47
48
+ ungetch (EOF );
48
49
ungetch ('A' );
49
50
ungetch ('B' );
50
51
ungetch ('C' );
51
52
ungetch ('D' );
52
- ungetch (EOF );
53
53
54
54
while ((c = getch ()) != EOF )
55
55
putchar (c );
You can’t perform that action at this time.
0 commit comments