aboutsummaryrefslogblamecommitdiff
path: root/5.2.c
blob: b0213f158c2aa33dd18e42f9c85855eb8e00df8e (plain) (tree)
1
2
3
4
5
6
7
8
9


                  
                   
 


                        
 


                    
 

                                     
 
                 

 
                       
 

                            
 

                                        
 



                                                                                              
 
                                       
 

                                           
 




                                                          
 

                                                      
 

                                                        
 

                                                                                       
 
                                             
 

                               
 

                     
 

                   
 


                                                 

 
                       
 



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

#define MAXBUFF 100

int getfloat(float *pn);
int getch(void);
void ungetch(int input);

int main(void)
{
        float input;

        getfloat(&input);
        printf("input: %f\n", input);

        return 0;
}

int getfloat(float *pn)
{
        char input, sign;
        int decimal_divider;

        while (isspace(input = getch()))
                ;

        if (!isdigit(input) && input != '.' && input != EOF && input != '+' && input != '-') {
                ungetch(input);
                return 0;
        }

        sign = (input == '-') ? -1 : 1;

        if (input == '-' || input == '+') {
                input = getch();

                if (!isdigit(input) && input != '.') {
                        ungetch((sign == -1) ? '-' : '+');
                        return 0;
                }
        }

        for (*pn = 0; isdigit(input); input = getch())
                *pn = (*pn * 10) + (input - '0');

        if (input == '.' && !isdigit(input = getchar()))
                ungetch('.');

        for (decimal_divider = 1; isdigit(input); input=getch(), decimal_divider *= 10)
                *pn = (*pn * 10) + (input - '0');

        *pn /= (float)decimal_divider * sign;

        if (input != EOF)
                ungetch(input);

        return input;
}

char buff[MAXBUFF];
int bpos = 0;

int getch(void)
{
        return (bpos) ? buff[--bpos] : getchar();
}

void ungetch(int input)
{
        if (bpos < MAXBUFF)
                buff[bpos++] = input;
        else
                printf("err: buff full\n");
}