Page 97
As written, getint
treats a +
or -
not followed by a digit as a valid
representation of zero. Fix it to push such a character back on the input.
#include <ctype.h>
#include <stdio.h>
#define SIZE 100
int main()
{
int n, isnum, array[SIZE], getint(int *);
for (n = 0; n < SIZE && (isnum = getint(&array[n])) != EOF;
isnum ? n++ : (void)0)
;
for (int i = 0; i < n; i++) {
printf("%d\n", array[i]);
}
}
int getch(void);
void ungetch(int);
int getint(int *pn)
{
int c, sign;
while (isspace(c = getch()))
;
if (!isdigit(c) && c != EOF && c != '+' && c != '-') {
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-') {
c = getch();
if (c <= '0' || c >= '9') {
return 0;
}
}
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;
}
}