shaobin0604
11/26/2009 - 7:18 AM

tcpl-ex-5-2.c

/*
 * Exercise 5-2. Write  getfloat, the floating-point analog of  getint. What 
 * type does getfloat return as its function value?  
 */
#include <stdio.h>
#include <ctype.h>

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

/* getfloat: get the next floating-point number from input */
int getfloat(float *pn)
{
	int c, sign;
	float power;

	while (isspace(c = getch())) /* skip white space */
		;
	if (!isdigit(c) && c != EOF && c != '+' && c != '-' && c != '.')
	{
		ungetch(c);
		return 0;
	}

	sign = (c == '-') ? -1 : 1;
	if (c == '+' || c == '-')
		c = getch();
	for (*pn = 0.0; isdigit(c); c = getch())
		*pn = *pn * 10 + (c - '0');				/* integer part */
	if (c == '.')
		c = getch();
	for (power = 1.0; isdigit(c); c = getch())
	{
		*pn = *pn * 10.0 + (c - '0');			/* fraction part */
		power *= 10;
	}
	*pn *= sign / power;						/* final number */
	if (c != EOF)
		ungetch(c);
	return c;
}