Programming Tutorials

getch and ungetch in C

By: Charles in C Tutorials on 2007-09-22  

What are getch and ungetch? It is often the case that a program cannot determine that it has read enough input until it has read too much. One instance is collecting characters that make up a number: until the first non-digit is seen, the number is not complete. But then the program has read one character too far, a character that it is not prepared for.

The problem would be solved if it were possible to ``un-read'' the unwanted character. Then, every time the program reads one character too many, it could push it back on the input, so the rest of the code could behave as if it had never been read. Fortunately, it's easy to simulate un-getting a character, by writing a pair of cooperating functions. getch delivers the next input character to be considered; ungetch will return them before reading new input.

How they work together is simple. ungetch puts the pushed-back characters into a shared buffer -- a character array. getch reads from the buffer if there is anything else, and calls getchar if the buffer is empty. There must also be an index variable that records the position of the current character in the buffer.

Since the buffer and the index are shared by getch and ungetch and must retain their values between calls, they must be external to both routines. Thus we can write getch, ungetch, and their shared variables as:

   #define BUFSIZE 100

   char 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;
   }
The standard library includes a function ungetch that provides one character of pushback;  We have used an array for the pushback, rather than a single character, to illustrate a more general approach.




Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C )

Latest Articles (in C)