Hello all. I am a CS major and I am learning recursion right now and have a lab assignment to write a program that uses recursion to evaluate post fix expressions. I have made an attempt at this but I am stuck and need some help. Here is what I have so far. I started by writing a function that took a simple expression in ex(24+) and output an answer(6). Now to make it recursive to evaluate more complex expressions. I have made it work part way. For instance if you input 2*(6+4) as 264+* you get an output of 10. So I feel I am headed in the right direction as it should first evaluate (6+4) and it gets that right but now I can't figure out how to make it do the next step. Any help is appreciated.
Here is code....
int postfix(string s){
cout<<s<<endl; // for debug
int a, b;
if (s.length() == 3 && !isdigit(s[s.length()-1] && isdigit(s[s.length()-2]))){
cout<<s<<endl; // for debug
a = s[0]-48;
b = s[1]-48;
cout<<"eval "<<a<<" "<<s[2]<<" "<<b<<endl;
switch (s[2]) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default :
cout<<"bad input\n";
}
} else {
return postfix(s.substr(1,s.length()-2));
}
return 0; // This return is for debug
}
Here is sample output....
Enter postfix expression: 264+*
264+*
64+
64+
eval 6 + 4
264+* = 10.