File tree 1 file changed +16
-21
lines changed
1 file changed +16
-21
lines changed Original file line number Diff line number Diff line change 2
2
* Exercise 4-8. Suppose that there will never be more than one character of
3
3
* pushback. Modify getch and ungetch accordingly.
4
4
*
5
- * NOTE: see alternate version 4-8a.c
6
- *
7
5
* Faisal Saadatmand
8
6
*/
9
7
10
8
#include <stdio.h>
11
- #include <stddef.h> /* for NULL */
12
9
13
10
/* functions */
14
11
int getch (void );
15
12
void ungetch (int );
16
13
17
14
/* globals */
18
- char buf ; /* buffer from ungetch */
19
- char * bufp = NULL ; /* pointer to buf */
15
+ int buf ; /* buffer from ungetch */
20
16
21
17
/* getch: get a (possibly pushed back) character */
22
18
int getch (void )
23
19
{
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 ;
32
28
}
33
29
34
30
/* ungerch: push character back on input */
35
31
void ungetch (int c )
36
32
{
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 ;
40
37
}
41
38
42
39
/* test getch */
43
40
int main (void )
44
41
{
45
42
ungetch ('A' );
46
- ungetch ('B' );
43
+ ungetch ('B' ); /* should give error */
44
+ printf ("%c\n" , getch ());
47
45
ungetch ('C' );
48
- ungetch ('D' );
49
-
50
- putchar (getch ());
51
- printf ("\n" );
46
+ printf ("%c\n" , getch ());
52
47
53
48
return 0 ;
54
49
}
You can’t perform that action at this time.
0 commit comments