Hatena::Groupcprogramming

C Study Diary

2009-01-09

c5ex2_getfloat.cpp

14:48

Write getfloat, the floating-point analog of getint . What type does getfloat return as its function value? Int

#include <stdio.h>
#include <ctype.h>
#define BUFSIZE 100

char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */

int getch(void) /* get a (possibly pushed back) character */
{
  return (bufp > 0) ? buf[--bufp] : getchar();
}
 
void ungetch(int c) /* push character back on input */
{
  if(bufp >= BUFSIZE)
    printf("ungetch: too many characters\n");
  else  
    buf[bufp++] = c;  
}


/* getint:  get next integer from input into *pn */
int getfloat(float *pn)
{
	int c, sign, signflag=0;
	float decimal=0.0, rate = 1;
	while (isspace(c = getch())) /* skip white space */
	;
	if (!isdigit(c) && c != EOF && c != '+' && c != '-'&& c != '.') {
		ungetch(c); /* it is not a number */
		return EOF;
	}
	sign = (c == '-') ? -1 : 1;
	if (c == '+' || c == '-') {
		c = getch();
		signflag = 1;
	}	
	/* if sign without number */
	if(!isdigit(c) && c != '.' && c!=EOF) {
		ungetch(c);
		if(signflag) ungetch(((sign==1) ? '+':'-'));
		return EOF;
	}else {	
		for (*pn = 0.0; isdigit(c); c = getch())
			*pn = 10.0 * *pn + (c - '0');
		/* point inputed */
		if(c=='.') {			
			c=getch();
			while(isdigit(c)){
				rate = rate*0.1; 
				decimal = decimal+(c-'0')*rate;
				c=getch();
			}
			*pn +=decimal;
		}	
		*pn *= sign;
		if (c != EOF)
			ungetch(c);
		return c;
	}
}

int main(){
	
	float pa[10]={};
	int	i=0;
	
	while(getfloat(&pa[i])!=EOF) {
		pa[i++];
		printf("input: %f\n\n",pa[i-1]);
	}
	return 0;
}

Run:

$ ./c5ex2_getfloat.exe
2
input: 2.000000

-222
input: -222.000000

2.22
input: 2.220000

-3.335
input: -3.335000