lolamontes69

K+R Exercise5_2

Sep 7th, 2014
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.68 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <ctype.h>
  3.  
  4. #define BUFSIZE 100
  5.  
  6. int getfloat(float *pn);
  7. int getch(void);
  8. void ungetch(int);
  9.  
  10. char buf[BUFSIZE];
  11. int bufp = 0;
  12.  
  13. main()
  14. {
  15.     float i = 29;
  16.     int j;
  17.     float *pn;
  18.    
  19.     pn = &i;
  20.     printf("Original i = %f\n",i);
  21.  
  22.     j = getfloat(pn);
  23.     if(j!=0)
  24.         printf("i is now   = %f\n",i);
  25.     /* Verify putting into buf */
  26.     i = getch();
  27.     if(bufp>0) {
  28.         puts("Print contents of buffer");
  29.         while(bufp >= 0) {
  30.             i = buf[bufp--];
  31.             printf("i = %c\n",i);
  32.         }
  33.     }
  34.     return(0);
  35. }
  36.  
  37. /* getint: get next integer from input into *pn */
  38. int getfloat(float *pn)
  39. {
  40.     int c, sign;
  41.     float f;
  42.    
  43.     while(isspace(c = getch()))
  44.         ;
  45.     if(!isdigit(c) && c != EOF && c!='+' && c!= '-') {
  46.         ungetch(c);
  47.         return 0;
  48.     }
  49.     sign = (c == '-') ? -1 : 1;
  50.     if(c=='+' || c=='-')
  51.         c = getch();
  52.     if(!isdigit(c)) {
  53.         (sign < 0) ? ungetch('-'): ungetch('+');
  54.         ungetch(c);
  55.         return 0;
  56.     }
  57.     for(*pn = 0; isdigit(c); c=getch())
  58.         *pn = 10 * *pn + (c-'0');
  59.     *pn *= sign;
  60.     /* Add the float part to the number */
  61.     if(c=='.') {
  62.         c=getch();  
  63.         for(f = 10.0; isdigit(c); c=getch()) {
  64.             *pn += (c-'0')/f;
  65.             f*=10;
  66.         }
  67.     }
  68.     if(c!=EOF)
  69.         ungetch(c);
  70.     return c;
  71. }
  72.  
  73. /* get a (possibly pushed-back) character */
  74. int getch(void)
  75. {
  76.     return (bufp > 0) ? buf[--bufp] : getchar();  
  77. }
  78.  
  79. /* push character back on input */
  80. void ungetch(int c)
  81. {
  82.     if(bufp >= BUFSIZE)
  83.         printf("ungetch: too many characters\n");
  84.     else
  85.         buf[bufp++] = c;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment