Thread: chapter 4 K&R, getch() and ungetch()

  1. #1
    Registered User blob84's Avatar
    Join Date
    Jun 2010
    Posts
    46

    chapter 4 K&R, getch() and ungetch()

    Hi, i have problem with these functions: getch() and ungetch(), pag 67 english 2 version K&R.
    Code:
    #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;
    }
    I do not post the entire code of the polish notation calculator, i assume you already know.
    What i have understood is:
    when getch is called, if the chars counter bufp is > 0, then return the prevoius char buf[--bufp], else call getchar(), this id done to not get back the wrong char, for example a non-digit;
    when ungetch is called it stores the characters in the array buf[buf++].
    I would be grateful if someone can explain how these functions work, with an example.
    Thanks.
    Last edited by blob84; 04-28-2011 at 04:35 AM.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    The first function reads like this:
    Code:
    if there is a character already in buf
        move the counter back one and then
        return the character that was in the buffer's last used spot
    else
        get a character using getchar
    The other one just checks to see if the buffer is full, and if it isn't, puts a character in it, updating the position of the end of the buffer.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. getch()
    By Stan100 in forum C++ Programming
    Replies: 7
    Last Post: 12-09-2002, 02:53 PM
  2. getch() twice??
    By ... in forum C++ Programming
    Replies: 7
    Last Post: 11-12-2002, 06:11 PM
  3. Visual C++ 6 Bible [Chapter 7]
    By Dual-Catfish in forum Windows Programming
    Replies: 6
    Last Post: 03-12-2002, 01:15 PM
  4. ungetch()
    By 0927 in forum C++ Programming
    Replies: 1
    Last Post: 01-16-2002, 10:35 PM
  5. differences between getch(), getche(), and ungetch()
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 01-08-2002, 02:08 AM