Cプログラミング言語(第2版)5-2

2023 ワード

#include <ctype.h>
#include <stdio.h>

#define BUFSIZE 100
char buf[BUFSIZE];    /* buffer for ungetch */
int bufp = 0;         /* next free position in buf */
int getch(void);
void ungetch(int);


   /* getint:  get next integer from input into *pn */
   double getdou(double *pn)
   {
       int c, sign;
       while (isspace(c = getch()))   /* skip white space */
           ;
	    if (!isdigit(c) && c != EOF && c != '+' && c != '-') {
           ungetch(c);  /* it is not a number */
           return 0;
       }
       sign = (c == '-') ? -1 : 1;
       if (c == '+' || c == '-')
           c = getch();
       for (*pn = 0;isdigit(c);c = getch())
           *pn = 10 * (*pn) + (c - '0');
	
	   //////////////////////////////////////////////////////////////////////
	   int power=1;
	   if(c=='.')
	   { 
		   c=getch();///!!!
		   for(power=1;isdigit(c);c=getch())
			{
				*pn = 10 * *pn + (c - '0');
				 power=10*power;
			}
	   }
	   if(power!=1)
		   *pn = 1.0 * (*pn)/power;
       *pn *= sign;
	   
       if (c != EOF)
           ungetch(c);
       return *pn;
   }


   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
"); else buf[bufp++] = c; } int main(){ double *num; num = new double; double number=getdou(num); printf("%g
",number); return 0; }