Encoders
>
More...
>
C
>
Program
/* Function getint(&a) to break a stream of characters into integer values,
one integer value per call such that '+' or '-' not followed by a digit
is treated as invalid number. */
#include <stdio.h>
int getint(int *);
main()
{
int a,c;
c=getint(&a);
printf("returned value as int = %d\ta=%d\n",c,a);
c = getint(&a);
printf("returned value as int = %d\ta=%d\n",c,a);
c = getint(&a);
printf("returned value as int = %d\ta=%d\n",c,a);
c = getint(&a);
printf("returned value as int = %d\ta=%d\n",c,a);
c = getint(&a);
printf("returned value as int = %d\ta=%d\n",c,a);
}
#include <ctype.h>
int getch(void);
void ungetch(int c);
int getint(int *pn)
{
int c, s, sign;
while(isspace(c=getch()))
;
if(!isdigit(c) && c!=EOF && c!='+' && c!='-')
{
ungetch(c);
return 0;
}
sign = c=='-'?-1:1;
if(c=='+' || c=='-')
{ s=c;
if(!isdigit(c=getch()))
{
if(c!=EOF)
ungetch(c);
ungetch(s);
return 0;
}
}
for(*pn=0; isdigit(c); c=getch())
*pn = *pn * 10 + (c - '0');
*pn *= sign;
if(c!=EOF)
ungetch(c);
return c;
}
char buf[100];
int bufp=0;
int getch(void)
{
return(bufp>0)?buf[--bufp]:getchar();
}
void ungetch(int c)
{
if(bufp>=100)
printf("error: buffer overflow\n");
else
buf[bufp++]=c;
}
|