In K&R, at the beginning of chapter 5, is presented the function getint that
performs free-format input conversion by breaking a stream of charachters into integer values, one integer per call.
The function is pretty simple, but i can't actually understand why is c
pushed back in to the buffer in the first if-statement
. Because of this, every time you call getint
it will do the same thing. Because it will read the next charachter in the buffer
, which is c
.
Is this strategy intended to be a kind of security mechanism?
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;
}