#include <stdio.h>
#include <ctype.h>
#define BUFSIZE 100
/* Implementation */
staticchar buf[BUFSIZE];
staticint bufp = 0;
int getch(void) {return (bufp > 0) ? buf[--bufp] : getchar();}
int ungetch(int c)
{
if (bufp >= (int)sizeof(buf))
return EOF;
else
buf[bufp++] = c;
}
/* 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's not a number */
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-')
c = getch();
if (!isdigit(c)) {
ungetch(c);
return 0;
}
for (*pn = 0; isdigit(c); c = getch())
*pn = 10 * *pn + (c - '0');
*pn *= sign;
if (c != EOF)
ungetch(c);
return c;
}
All programming must be done in C, but how could I test this?
The original getint treated + or - not followed by a digit as a valid representation of zero. Now I fixed it to push such character back on the input.
Can you provide a complete program please? To test, whether the character is pushed successfully back on the input, I think I need something like this: