/* * Function-plotting program. Has five functions (identity, odd, square, * cubic, sine) and you can plot them at different scales. * I put in the 'help' facility in all full glory as an example. */ #include #include "plot.h" #include "functions.h" struct { char *name; double (*function)(double); char *description; } functions[] = { { "identity", identity, "the identity function" }, { "odd", odd, "shows which values are odd" }, { "square", square, "y**2" }, { "cubic", cubic, "y**3 - 2y + 1" }, { "sine", sine, "sine function (actually 3sin(y) to look better)" }, }; enum parsestatus { valid, /* valid input, proceed to plot */ blank, /* blank line, ignore */ syntax, /* syntax error */ nosuch /* syntax is ok but there is no such function */ }; int main() { extern enum parsestatus parse(char *s, double (**fp)(double), double *scale); char buf[80]; double (*f)(double); double scale; while (fgets(buf, sizeof buf, stdin)) { switch (parse(buf, &f, &scale)) { case valid: plot(f, scale); break; case blank: break; case syntax: printf("syntax error -- type 'help' for help\n"); break; case nosuch: printf("no such function -- type 'help' for a list\n"); break; } } return 0; } enum parsestatus parse(char *s, double (**fp)(double), double *scale) { char name[80]; int i; extern void help(); switch (sscanf(s, "%79s%lg", name, scale)) { case 1: *scale = 10; break; case 2: break; default: return (s[0] == '\n') ? blank : syntax; } if (strcmp(name, "quit") == 0) exit(0); if (strcmp(name, "help") == 0) { help(); return blank; } for (i = 0; i < sizeof functions / sizeof functions[0]; i++) { if (strcmp(name, functions[i].name) == 0) { *fp = functions[i].function; return valid; } } return nosuch; } void help() { int i; printf("Type a function name, followed by an optional scaling factor.\n"); printf("(Separate the function name from the scale with a space.)\n"); printf("The default scale is 10. The functions are:\n"); for (i = 0; i < sizeof functions / sizeof functions[0]; i++) printf(" %s - %s\n", functions[i].name, functions[i].description); printf("Type quit to quit.\n"); }