I tried to understand the work of this code for 2 days, but I just can’t wrap it around me.
I doubt the function works. Please do not take into account the lack of basic or something else.
I do not understand that if getint () accepts input using getchar (), it will do the following:
- Let's say bufp = 0. The function will call getch (), which means c = a. (Random character only)
- The next step is with ungetch (a), which means buf [0] = a and bufp = 1.
- Now I can’t get it. The next time getint () is called, c = buf [- bufp] = a and bufp = 0.
- This will again disable (a), which will make the function unavailable!
I don't know if there are some basic concepts here, but I just can't figure it out. :(
int getint(int *pn)
{
int c, sign;
while (isspace(c = getch()))
;
if (!isdigit(c) && c != EOF && c != '+' && c != '-') {
ungetch(c);
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];
int bufp = 0;
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c)
{
if(bufp >= BUFSIZE)
printf(" ungetch too many characters\n");
else
buf[bufp++] = c;
}