I made a small Scheme interpreter(without functions and other fancy stuff) a while ago but ran into a few problems. Anyways here's the source:
The biggest problem if the scanf in eval() doesn't quite do what I wanted. Instead of reading the whole (...) expression, only the characters up to the first space are read. Can anyone think of a good solution to this? The other problem is I'm getting a seg fault somewhere but I can't seem to find it.Code:#include <ctype.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int eval(char *s); int isnumber(char *s); int main(void) { char e[201]; for(;;) { printf("<"); fgets(e, 200, stdin); printf(">%d\n", eval(e)); } return EXIT_SUCCESS; } int eval(char *s) { int ans; int narg[2]; char sarg[2][101]; int i; char op; sscanf(s, "(%c %100s %100s)", &op, sarg[0], sarg[1]); narg[0] = isnumber(sarg[0]) ? atoi(sarg[0]) : eval(sarg[0]); narg[1] = isnumber(sarg[1]) ? atoi(sarg[1]) : eval(sarg[1]); switch(op) { case '+': ans = narg[0] + narg[1]; break; case '-': ans = narg[0] - narg[1]; break; case '*': ans = narg[0] * narg[1]; break; case '/': ans = narg[0] / narg[1]; break; } return ans; } int isnumber(char *s) { int i; for(i = 0; s[i] != '\0'; i++) { if(!isdigit(s[i])) { return 0; } } return 1; }



LinkBack URL
About LinkBacks



