Answer to Question #203486 in C++ for Talha

Question #203486

Task 1

Solve this problem using stacks, Implementation other than stack will leads to zero

marks

Write a class ex_conversion in C++ to evaluate postfix expressions. You will have to

implement following methods.

1. InputEx – will let the user enter the postfix expression in character array to

be evaluated.

Enter the expression: abc*+d-

2. ReadVar – will read the values of variables a,b,c,d . . . z from file (“data.txt”)

and return true on successful read.

10 20 30 40 50 60 . . . 26

3. EvaluateEx – will evaluate the expression and return the answer or display

the error message.


1
Expert's answer
2021-06-05T02:14:15-0400
#include<iostream>
#include<cmath>
#include<stack>
using namespace std;
float scanningNum(char c) {
   int val;
   val = c;
   return float(val-'0');   
}
int is_operator(char c) {
   if(c == '+'|| c == '-'|| c == '*'|| c == '/' || c == '^')
      return 1; 
   return -1;   
}
int is_operand(char c) {
   if(c>= '0' && c <= '9')
      return 1;   
   return -1; 
}
float operation(int y, int x, char op) {
   if(op == '+')
      return x+y;
   else if(op == '-')
      return x-y;
   else if(op == '*')
      return x*y;
   else if(op == '/')
      return x/y;
   else if(op == '^')
      return pow(x,y);
   else
      return 0;
}
float EvaluateEx(string postfix) {
   int a, b;
   stack<float> s;
   string::iterator i;
   for(i=postfix.begin(); i!=postfix.end(); i++) {
      if(is_operator(*i) != -1) {
         a = s.top();
         s.pop();
         b = s.top();
         s.pop();
         s.push(operation(a, b, *i));
      }else if(is_operand(*i) > 0) {
         s.push(scanningNum(*i));
      }
   }
   return s.top();
}
main() {
   string post_exp = "674*+9-";
   cout << "The result is: "<<EvaluateEx(post_exp);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog