Blob


1 /*
2 * Exercise 4-9. Our getch and ungetch do not handle a pushed-back EOF
3 * correctly. Decide what their properties ought to be if an EOF is pushed
4 * back, then implement your design.
5 *
6 * EOF is defined as -1, so we need to change the buffer from an array of
7 * chars to an array of ints. The functions are otherwise identical
8 */
10 #include <stdio.h>
11 #include <string.h>
13 #define MAXLEN 1000 /* max size of buffer */
15 int getch(void);
16 void ungetch(int);
17 void ungets(char []);
19 int main() {
20 char s[MAXLEN];
21 int i = 0;
22 char c;
23 while ((s[i++] = c = getch()) != EOF) {
24 if (c == '*') {
25 ungets("test");
26 i--;
27 }
28 }
29 s[i] = '\0';
30 printf("%s\n", s);
31 }
33 #define BUFSIZE 100
35 int buf[BUFSIZE]; /* buffer for ungetch */
36 int bufp = 0;
38 /* get a (possibly pushed back) character */
39 int getch(void) {
40 return (bufp > 0) ? buf[--bufp] : getchar();
41 }
43 /* push character back on input */
44 void ungetch(int c) {
45 if (bufp >= BUFSIZE)
46 printf("ungetch: too many characters\n");
47 else
48 buf[bufp++] = c;
49 }
51 void ungets(char s[]) {
52 int i = strlen(s);
53 while (i > 0)
54 ungetch(s[--i]);
55 }