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:
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;
}
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.
it makes sense to me you are confusing your function names
getch != getchar getint != getop
get some sleep
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With