aboutsummaryrefslogtreecommitdiff
path: root/5.6.1.c
blob: 1810198b31ab72e38d238f8bdfa34bacf310f7e2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <ctype.h>

#define MAXLEN 64

int sneed_getline(char str[], int max);
double atof(const char str[]);

int 
main(void)
{
  char str[MAXLEN];

  while (sneed_getline(str, MAXLEN) > 0)
    printf("%f\n\n", atof(str));

  return 0;
}

int
sneed_getline(char str[], int max)
{
  char input;
  char *str_og = str;

  while (--max && (*str = input = getchar()) != EOF && input != '\n')
    str++;

  if (!max && input != '\n')
    *str = '\n', str++;

  str = '\0';

  return str - str_og;
}

double 
atof(const char str[])
{
  int i, sign, e_sign, j;
  double val, power, e_power;

  for (i = 0; isspace(str[i]); i++)
    ;
  sign = (str[i] == '-') ? -1 : 1;

  if (str[i] == '-' || str[i] == '+')
    i++;

  for(val = 0.0; isdigit(str[i]); i++)
    val = val * 10.0 + (str[i] - '0');

  if (str[i] == '.')
    i++;

  for(power = 1.0; isdigit(str[i]); i++) {
    val = 10 * val + (str[i] - '0');
    power *= 10.0;
  }

  if (str[i] == 'e' || str[i] == 'E')
    i++;

  e_sign = (str[i] == '-') ? -1 : 1;

  if (str[i] == '-' || str[i] == '+')
    i++;

  for (e_power = 0.0; isdigit(str[i]); i++)
    e_power = e_power * 10 + (str[i] - '0');

  if (e_sign < 0)
    for (j = 0; j < e_power; j++)
      power *= 10.0;
  else
    for (j = 0; j < e_power; j++)
      power /= 10.0;

  return (sign * val / power);
}