I am starting to develop a calculator in C++ which accepts the expression in the form:
2+3 or
2/3 ,etc. ( for the time being, only two operands and one operator) Once i get that done, I will begin the process of continuely expanding it :)
The problem I am having is, that I read the book by Stroustrup, and there was an entire chap on it on Low level input. And since I have read that, my brain has gotten trapped and I continuely am adopting the same procedure to make my own program.
Here is the code:
#include<iostream>
using namespace std;
enum Type_exp{ PRINT,NUM, PLUS='+',MINUS='-',DIV='/',MUL='*',SPACE,END};
Type_exp curr_exp=END;
double num;
Type_exp getexp();
double oper();
int main()
{
double ans;
cout<<"Enter the expression to evaluate";
ans=oper();
cout<<endl<<endl<<ans;
return 0;
}
Type_exp getexp()
{
char ch=0;
cin>>ch;
switch(ch)
{
case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 0:
cin.putback(ch);
cin>>num;
return curr_exp=NUM;
case '+': return curr_exp=PLUS;
case '-': return curr_exp=MINUS;
case '/': return curr_exp=DIV;
case '*': return curr_exp=MUL;
case '\n':
case ';': return curr_exp=PRINT;
}
}
double oper()
{
getexp();
double left;
while(curr_exp!=PRINT)
{
switch(curr_exp)
{
case PRINT:
return left;
case NUM:
left=num;
getexp();
break;
case PLUS:
getexp();
while(curr_exp==SPACE)
getexp();
left+=num;
getexp();
break;
case MINUS:
getexp();
while(curr_exp==SPACE)
getexp();
left-=num;
getexp();
break;
case DIV:
getexp();
while(curr_exp==SPACE)
getexp();
left/=num;
getexp();
break;
case MUL:
getexp();
while(curr_exp==SPACE)
getexp();
left*=num;
getexp();
break;
}
}
}
Any help would be greatly appreciated:)