-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy path4-7.c
70 lines (59 loc) · 1.5 KB
/
4-7.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* Exercise 4-7. Write a routine ungets(s) that will push back an entire string
* onto the input. Should ungets know about buf and bufp, or should it just use
* ungetch?
*
* Answer: on one hand, the only clear advantage in ungets gaining direct
* access to buf and bufp seems to be the ability to print the error message
* directly rather than through ungetch. On the other, since ungetc is just
* ungetch wrapped in a for loop, it makes sense to use ungetch and reduce code
* duplication.
*
* Faisal Saadatmand
*/
#include <stdio.h>
#include <string.h> /* for strlen() */
#define BUFSIZE 100
#define MAXLEN 10000
/* functions */
int getch(void);
void ungetch(int);
void ungets(char []);
/* globals */
char buf[BUFSIZE]; /* buffer from ungetch */
int bufp = 0; /* next free position in buf */
/* getch: get a (possibly pushed back) character */
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
/* ungerch: push character back on input */
void ungetch(int c)
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
/* ungets: push back s onto the input */
void ungets(char s[])
{
int i;
for (i = strlen(s) - 1; i >= 0 ; --i)
ungetch(s[i]);
}
/* test ungets */
int main(void)
{
int c, i;
char s[MAXLEN];
printf("Enter string to test ungets function:\n");
for (i = 0; (s[i] = getch()) != '\n'; i++)
;
s[i++] ='\n';
s[i] = '\0';
ungets(s);
while ((c = getch()) != EOF)
putchar(c);
return 0;
}