Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't understand the working of getint() in C as per K&R

Tags:

c

I've been tried to understand the working of this code for 2 days now, but just can't wrap my head around it.

My doubt is about the working of the function. Please don't take the absence of main or anything else into consideration.

What I can't understand is that if getint() takes input with getchar() it will do the following:

  1. Let's say bufp=0. The function will call getch(), which means c=a. (Just a random character)
  2. The next step with ungetch(a), which means buf[0]=a and bufp=1.
  3. Now this is where I can't get it. The next time getint() is called, c=buf[--bufp]=a and bufp=0 as a result.
  4. This will then again ungetch(a), which will result lead the function nowhere!

I don't know if I have some major concept(s) wrong here, but I just can't figure it out. :(

/* getint:  get next integer from input into *pn */

int getint(int *pn)
{
    int c, sign;

    while (isspace(c = getch()))   /* skip white space */
            ;

    if (!isdigit(c) && c != EOF && c != '+' && c != '-') {
            ungetch(c);  /* it is not a number */
            return 0;
    }
    sign = (c == '-') ? -1 : 1;
    if (c == '+' || c == '-')
            c = getch();
    for (*pn = 0; isdigit(c); c = getch())
            *pn = 10 * *pn + (c - '0');
    *pn *= sign;
    if (c != EOF)
            ungetch(c);
    return c;
}

#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;
}
like image 714
Zygote Avatar asked Apr 16 '12 07:04

Zygote


3 Answers

The getint() function only reads digits from the input. If it gets a character that is not a digit or a + - sign at the beginning it will call ungetch() to push the character back into the input buffer so it could be read by some other function call. getint() will go on returning 0 until you remove the non-digit character from the input buffer by calling getch() on your own.

like image 95
smichak Avatar answered Sep 30 '22 05:09

smichak


it makes sense to me you are confusing your function names

getch != getchar getint != getop

get some sleep

like image 25
Paddy Carroll Avatar answered Sep 30 '22 05:09

Paddy Carroll


If getint() fails (and thus use ungetch in the scenario you give), calling again getint() will fail again. You are expected to call another function which will consume the pending character and make something usefull from the data which can't be interpreted as an int.

like image 39
AProgrammer Avatar answered Sep 30 '22 06:09

AProgrammer