Blob


1 /*
2 * Exercise 4-7. Write a routine ungets(s) that will push back an entire string
3 * onto the input. Should ungets know about buf and bufp, or should it just use
4 * ungetch?
5 *
6 * Just use ungetch so that the data structure for buf can be changed in
7 * the future
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 char 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 }