topic description
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 th input.
sources of topics and their own ideas
from Kmurr
related codes
-sharpinclude<ctype.h>
-sharpinclude<stdio.h>
-sharpdefine SIZE 100
int getch(void);
void ungetch(int c);
/* getint : get next integer from input into *pn */
int getint(int *pn)
{
int c,sign=1;
int d;
while(isspace(c = getch())) /*skip space */
;
if(!isdigit(c) && c!=EOF && c!="-" && c!="+")
{
ungetch(c);
return c; /* It is not a integer */
}
sign = (c == "-")? -1: 1;
if(c == "-" || c == "+")
{
d = c;
if(!isdigit(c = getch()))
{
if( c != EOF)
ungetch(c);
ungetch(d);
return d;
}
}
for(*pn = 0; isdigit(c); c =getch())
*pn = 10 * *pn + (c - "0");
*pn *= sign;
if( c != EOF)
ungetch(c);
return c;
}
int main()
{
int n;
int array[SIZE];
int last = 0;
int j;
int getint(int *pn);
for(n = 0; n < SIZE && getint(&array[n]) != EOF; nPP)
;
for(last =n ,j = 0; j < last; jPP)
printf("%d\t",array[j]);
printf("%d",j);
return 0;
}
-sharpdefine BUFSIZE 100
int buf[BUFSIZE]; /* buffer */
int bufp = 0;
int getch(void)
{
if( bufp > 0)
return buf[--bufp];
else
return getchar();
}
void ungetch(int c)
{
if(bufp < BUFSIZE)
buf[bufpPP] = c;
else
printf("error : too many characters\n");
}
what result do you expect? What is the error message actually seen?
when I type:
/ /-5
or
/ / + 5
and the letter, the program will stop immediately. Why?
if(c == "-" || c == "+")
{
d = c;
if(!isdigit(c = getch()))
{
if( c != EOF)
ungetch(c);
ungetch(d);
return d;
}
}
I think the logic works in this part.
when you enter: + 5
it is stored in the cache, isn"t it: (space) + 5?
I specially added a variable j to the main function to determine how many times the getint function was called. I found that it was called 100 times, but some array elements were not assigned initial values? Isn"t that the statement in the getint function?
for(*pn = 0; isdigit(c); c =getch())
*pn = 10 * *pn + (c - "0");
sincerely solve the problem, hope to get the answer, thank you!