Advertisement
clairec

Untitled

Aug 28th, 2017
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. /////////////////////////////////////////////
  2. //// Interpreter for simplified infix expression with +,-,*,/.
  3. //// Keyboard input, single digit numbers only and no spaces are allowed.
  4. //// compile:  $>g++ prog1.cpp
  5. //// run with: >2+3*4/2+3+4*2
  6. /////////////////////////////////////////////
  7.  
  8. #include <cstdlib> //for atoi()
  9. #include <iostream>
  10. using namespace std;
  11.  
  12. int Exp(), Term(), Exp2(int), Term2(int), Fact();
  13. string prog; //string for reading 1-line input program
  14. int indexx = 0; //global index for program string
  15.  
  16. int main(int argc, const char **argv)
  17. { cout<<">";
  18.   cin>>prog;  //reads 1-line input expression (program)
  19.   cout<<"result= "<<Exp()<<endl;
  20. }
  21.  
  22. int Exp()
  23. { return Exp2(Term());
  24. }
  25.  
  26. int Term()
  27. { return Term2(Fact());
  28. }
  29.  
  30. int Exp2(int inp)
  31. { int result = inp;
  32.   if (indexx < prog.length())   //if not the end of program string
  33.   { char a = prog.at(indexx++); //get one chr from program string
  34.     if (a == '+')
  35.       result = Exp2(result + Term());  //handles T+T
  36.     else if (a == '-')
  37.       result = Exp2(result - Term());  //handles T-T
  38.   }
  39.   return result;
  40. }
  41.  
  42. int Term2(int inp)
  43. { int result = inp;
  44.   if (indexx < prog.length())   //if not the end of program string
  45.   { char a = prog.at(indexx++); //get one chr from program string
  46.     if (a == '*')
  47.       result = Term2(result * Fact()); //handles consecutive * operators
  48.     else if (a == '/')
  49.       result = Term2(result / Fact()); //handles consecutive / operators
  50.     else if (a == '+' || a == '-')     //if + or -, get back one position
  51.       indexx--;
  52.   }
  53.   return result;
  54. }
  55.  
  56. int Fact()
  57. { char a = prog.at(indexx++); //get one chr from program string
  58.   return atoi(&a); //converts a char to a numeric number and return
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement