lolamontes69

K+R Exercise4_2

Sep 7th, 2014
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.95 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <ctype.h>
  3.  
  4. #define MAXLINE 1000
  5.  
  6. int getline(char line[], int max);
  7. double atof(char s[]);
  8.  
  9.  
  10. /* find all lines matching a pattern */
  11. main()
  12. {
  13.     char line[MAXLINE];            // line declared here is altered by passing it to getline
  14.                                    // in getline it is known as s
  15.     double res;
  16.  
  17.     while(getline(line, MAXLINE) > 0) {
  18.         res = atof(line);
  19.         printf("atof returns %g\n",res);
  20.     }
  21.     return (0);
  22. }
  23.  
  24. /* getline: get line into s, return length */
  25. int getline(char s[], int lim)
  26. {
  27.     int c, i;
  28.  
  29.     i=0;
  30.     while(--lim > 0 && (c=getchar())!=EOF && c!='\n')
  31.         s[i++] = c;
  32.     if(c=='\n')
  33.         ;
  34.     s[i]='\0';
  35.     return i;
  36. }
  37.  
  38. /* atof: convert string to double */
  39. double atof(char s[])
  40. {
  41.     double val, power, res;
  42.     int i, sign, sign2, expo;
  43.  
  44.     for(i=0; isspace(s[i]); i++) /* skip whitespace */
  45.         ;
  46.     sign = (s[i] == '-') ? -1 : 1;
  47.     if(s[i] == '+' || s[i] == '-')
  48.         i++;
  49.     for(val=0.0; isdigit(s[i]); i++){
  50.         val=(10.0*val)+(s[i]-'0');
  51.     }
  52.     if(s[i]=='.')
  53.         i++;
  54.     for(power=1.0; isdigit(s[i]); i++) {
  55.         val=(10.0*val)+(s[i]-'0');
  56.         power*=10;
  57.     }
  58.     if(s[i]=='e' || s[i]=='E') {
  59.         i++;
  60.         /* see if its signed else assume it's positive */
  61.         sign2 = 0;
  62.         if(s[i]=='-') {
  63.             sign2=1;
  64.             i++;
  65.         }
  66.         else if(s[i]=='+')
  67.             i++;
  68.         for(expo=0; isdigit(s[i]); i++){
  69.             expo=(10*expo)+(s[i]-'0');
  70.         }
  71.         res = sign*val/power;
  72.         if(sign2==1) {
  73.             for(i=0; i<expo; i++)   // 1.000000e-07 = 0.0000001
  74.                 res = res/10.0;
  75.             return res;
  76.         }
  77.         else {
  78.             for(i=0; i<expo; i++)   // a = 1000000  = 1.000000e+06
  79.                 res = res*10.0;
  80.             return res;
  81.         }                            
  82.     }
  83.     return sign*val/power;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment