"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."
Ok, well this is the original version:
int getint2(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;
ungetch(c);
return c;
}
And i edited this way:
int getint2(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();
if(!isdigit(c)) {
ungetch(c);
return 0;
}
}
for(*pn = 0; isdigit(c); c = getch())
*pn = 10 * *pn + (c - '0');
*pn *= sign;
ungetch(c);
return c;
}
So im not sure what did the author want. Should i unget the +/- aswell, or just the character after it? Should i return 0 in case there's no digits after +/- or -1?
I also have a question about getch and ungetch functions: since EOF on my sistem is -1, this is how i wrote getch and ungetch:
int buf = EOF;
int getch()
{
int temp;
if(buf == -2)
return EOF;
if(buf == EOF)
temp = getchar();
else
{
temp = buf;
buf = EOF;
}
return temp;
}
void ungetch(int c)
{
if(c == EOF)
buf = -2;
buf = c;
}
So i was told by some people that EOF can be -2. What should i do to avoid this sort of 'problem'.