The C Programming Language

Chapter 4 - Functions and Program Structure 9

mmresult 2009. 3. 27. 13:57


Our getch and ungetch do not handle a pushed-back EOF correctly. Decide what their properties ought to be if an EOF is pushed back, then implement your design.

Solution by Franz Fritsche. (Comment: The solution is virtually identical with the solution given by Tondo/Gimpel in their C Answer Book. Alas, what can I do?)

/* K&R Exercise 4-9 */
/* Franz Fritsche */

#include <stdio.h>

#define BUFSIZE 100

int buf[BUFSIZE];     /* buffer for ungetch */
int bufp = 0;         /* next free position in buf */

int getch(void)  /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c)   /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

Solution by Jesus Alvarez

#include <stdio.h>
#include <string.h>

int    getch    (void);
void   ungetch  (int);

/*
 * In the case that EOF is pushed back to ungetch(), the program will simply
 * continue execution as it normally would. Ignoring the EOF.
 */
int main()
{
        char c;

        /* Prematurely send EOF. */
        ungetch(EOF);

        while ((c = getch()) != EOF) {
                putchar(c);
        };

        return 0;
}

#define BUFSIZE 100
char buf[BUFSIZE];      /* Buffer for ungetch. */
int bufp = 0;           /* Next free position in buf. */

int getch(void)
{
        return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c)
{
        if (bufp >= BUFSIZE) {
                printf("Ungetch: Too many characters.\n");
        /*
         * The check for EOF must be made here. If EOF is found, it is ignored.
         */
        } else if (c != EOF) {
                buf[bufp++] = c;
        }
}


menonsahab's

/* The reason why the code in K&R can't handle EOF is because it is defined as follows:
#define EOF -1
i.e. its value is negative and a char array can't hold a negative value.
Change the buffer type to int and the problem is solved. */

#include <stdio.h>
#define BUFSIZE 100

int buf[BUFSIZE];
int bufp = 0;

int getch(void)
{
 return bufp > 0 ? buf[--bufp] : getchar();
}

void ungetch(int c)
{
 if(bufp >= BUFSIZE)
  printf("error: stack is full, can't execute ungetch()\n");
 else
  buf[bufp++] = c;
}