clairec icon

Untitled

clairec | PRO | 08/28/17 07:30:09 PM UTC | 0 ⭐ | 573 👁️ | Never ⏰ | []
C++ |

1.72 KB

|

None

|

0 👍

/

0 👎

/////////////////////////////////////////////
//// Interpreter for simplified infix expression with +,-,*,/.
//// Keyboard input, single digit numbers only and no spaces are allowed.
//// compile:  $>g++ prog1.cpp
//// run with: >2+3*4/2+3+4*2
/////////////////////////////////////////////
 
#include <cstdlib> //for atoi()
#include <iostream>
using namespace std;
 
int Exp(), Term(), Exp2(int), Term2(int), Fact();
string prog; //string for reading 1-line input program
int indexx = 0; //global index for program string
 
int main(int argc, const char **argv)
{ cout<<">";
  cin>>prog;  //reads 1-line input expression (program)
  cout<<"result= "<<Exp()<<endl;
}
 
int Exp()
{ return Exp2(Term());
}
 
int Term()
{ return Term2(Fact());
}
 
int Exp2(int inp)
{ int result = inp;
  if (indexx < prog.length())   //if not the end of program string
  { char a = prog.at(indexx++); //get one chr from program string
    if (a == '+')
      result = Exp2(result + Term());  //handles T+T
    else if (a == '-')
      result = Exp2(result - Term());  //handles T-T
  }
  return result;
}
 
int Term2(int inp)
{ int result = inp;
  if (indexx < prog.length())   //if not the end of program string
  { char a = prog.at(indexx++); //get one chr from program string
    if (a == '*')
      result = Term2(result * Fact()); //handles consecutive * operators
    else if (a == '/')
      result = Term2(result / Fact()); //handles consecutive / operators
    else if (a == '+' || a == '-')     //if + or -, get back one position
      indexx--;
  }
  return result;
}
 
int Fact()
{ char a = prog.at(indexx++); //get one chr from program string
  return atoi(&a); //converts a char to a numeric number and return
}

Comments