Encoders
Hub for Computer Whizzes Register to join us

Encoders > More... > C > Program

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

#include <stdio.h>

int getfloat(float *);

main()
{
	float a;
	int c;
        c=getint(&a);
        printf("returned value as int = %d\ta=%f\n",c,a);
        c = getint(&a);
        printf("returned value as int = %d\ta=%f\n",c,a);
        c = getint(&a);
        printf("returned value as int = %d\ta=%f\n",c,a);
        c = getint(&a);
        printf("returned value as int = %d\ta=%f\n",c,a);
        c = getint(&a);
        printf("returned value as int = %d\ta=%f\n",c,a);
}

#include <ctype.h>

int getch(void);
void ungetch(int c);

int getfloat(float  *pn)
{
	float power[2];
	int c, sign[2], exp;
	while(isspace(c=getch()))
		;
        if(!isdigit(c) && c!=EOF && c!='+' && c!='-' && c!='.')
	{
		ungetch(c);
		return 0;
	}
	sign[0] = c=='-'?-1:1;
	if(c=='+' || c=='-')
		c=getch();
	for(*pn=0; isdigit(c); c=getch())
		*pn = *pn * 10 + c - '0';
	if(c=='.')
		c=getch();
	for(power[0]=1; isdigit(c); c=getch())
	{
		*pn = *pn * 10 + c - '0';
		power[0] *= 10;
	}
	if(tolower(c)=='e')
		c=getch();
	sign[1] = c=='-'?-1:1;
	if(c=='+' || c=='-')
		c=getch();
	for(exp=0; isdigit(c); c=getch())
		exp = exp*10 + c-'0';
        for(power[1]=1; exp>0; exp--)
		power[1] *= sign[1]==1?10:1./10;
	*pn = sign[0] * *pn/power[0] * power[1];
	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;
}