Encoders
Hub for Computer Whizzes Register to join us

Encoders > More... > C > Program

/* Function getint(&a) to break a stream of characters into integer values,
   one integer value per call. */

#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, 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 = *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;
}