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

#include <sdtio.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 character back into the input     */
void ungetch(int c){
    if (buf != 0)
       printf("ungetch: too many characters\n");
   else
      buf = c;
}

Leave a comment