index
 1  /**************************************************
 2  * file: calc.cpp
 3  * date: 2006-06-30
 4  * author: ideawu
 5  * describe: a really small and simple caculator.
 6  *           with known bugs.
 7  **************************************************/
 8
 9  #include <stdio.h>
10  #include <stdlib.h>
11  #include <string.h>
12
13  #include "Parser.h"
14
15  float calc(SyntaxTree *tree);
16
17  int main(int argc, char* argv[]){
18      char buf[1024] = "a=";
19      SyntaxTree *tree = NULL;
20      Lexer *lexer = new Lexer();
21      Parser *parser = new Parser();
22
23      lexer->setSrc(buf, 1024);
24      parser->setLexer(lexer);
25
26      printf(">>");
27      scanf("%s", &buf[2]);
28      while(strcmp(buf, "a=quit") != 0){
29          tree = parser->parse();
30
31          if(tree!=NULL){
32              //tree->display();
33              printf("%g\n", calc(tree->getRight()));
34          }else{
35              parser->printError();
36          }
37          printf(">>");
38          scanf("%s", &buf[2]);
39          parser->reset();
40      }
41
42      printf("\n");
43
44      return 0;
45  }
46
47  float calc(SyntaxTree *tree){
48      float a=0, b=0, val=0;
49
50      if(tree != NULL){
51          if(tree->getRootNode()->getType() == NUM){
52              return tree->getRootNode()->getValue();
53          }
54          a = calc(tree->getLeft());
55          b = calc(tree->getRight());
56
57          switch(tree->getRootNode()->getType()){
58              case PLUS:
59                  val = a + b;
60                  break;
61              case MINUS:
62                  val = a - b;
63                  break;
64              case MUL:
65                  val = a * b;
66                  break;
67              case DIV:
68                  if(b != 0){
69                      val = a / b;
70                  }
71                  break;
72              default:
73                  break;
74          }
75      }
76
77      return val;
78
79  }
80
81