diff options
-rw-r--r-- | 4.1.c | 61 | ||||
-rw-r--r-- | 4.2.c | 80 |
2 files changed, 141 insertions, 0 deletions
@@ -0,0 +1,61 @@ +#include <stdio.h> + +#define MAXLEN 1000 + +int get_line(char line[], const int max); +int strindex(char source[], char pattern[]); + +int +main(void) +{ + int found, rightmost; + char line[MAXLEN]; + + char pattern[] = "ould"; + found = 0; + + while (get_line(line, MAXLEN) > 0) + if ((rightmost = strindex(line, pattern)) >= 0) { + printf("%s >> match at char %d\n", line, rightmost+1); + found++; + } + + printf("\nSneedGrep found %d match%s\n", found, (found > 0) ? "es" : ""); + + return 0; +} + +int +get_line(char line[], const int max) +{ + int i; + char input; + + for (i = 0; (input = getchar()) != EOF && input != '\n' && i < max-2; i++) + line[i] = input; + + if (input == '\n' && i < max-2) + line[i++] = '\n'; + + line[i] = '\0'; + + return i; +} + +int +strindex(char source[], char pattern[]) +{ + int i, j, k, rightmost; + + rightmost = -1; + + for (i = 0; source[i] != '\0'; i++) { + for (j = i, k = 0; pattern[k] != '\0' && source[j] == pattern[k]; j++, k++) + ; + + if (pattern[k] == '\0') + rightmost = i; + } + + return rightmost; +} @@ -0,0 +1,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) +{ + int i; + char input; + + for (i = 0; i < max && (input = getchar()) != EOF && input != '\n'; i++) + str[i] = input; + + if (i < max && input != '\n') + str[i++] = '\n'; + + str[i] = '\0'; + + return i; +} + +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; + else + for (j = 0; j < e_power; j++) + power /= 10; + + return (sign * val / power); +} |