Exercise 4.8 - getch and ungetch handling pushback character

Question

Suppose that there will never be more than one character of pushback. Modify getch and ungetch accordingly.

/**
 * Suppose that there will never be more than one character
 * for pushback. Modify getch and ungetch accordingly.
 **/

#include <stdio.h>

char buf = 0;

/* getch: get a (possibly) pushed back character */
int getch(void)
{
	int c;

	if(buf != 0)
		c = buf;
	else
		c = getchar();

	buf = 0;
	return c;
}

/* ungetch: push a character back into input */
void ungetch(int c)
{
	if(buf != 0)
		printf("ungetch: too many characters\n");
	else
		buf = c;
}

int main(void)
{
	int c;

	c = '*';

	ungetch(c);

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

	return 0;
}

Explanation

This program maintains a character buffer char buf=0 which holds a single character from the input. The function ungetch(c) when called places the character in the input and getch(), if it finds the character in the buf, returns it or it calls getchar to get character from the user.

Visualize It

Try It