Advertisement
skb50bd

Reversed Polish

Dec 11th, 2015
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. Evaluate the Value of a Reversed Polish Notation String
  2.  
  3.  
  4. #include <iostream>
  5. #include <stack>
  6. #include <sstream>
  7. #include <cstdlib>
  8. #include <cmath>
  9. using namespace std ;
  10.  
  11.  
  12. void pop(double &first, double &second, stack <double> &S) {
  13.     second = S.top();
  14.     S.pop();
  15.     first = S.top();
  16.     S.pop();
  17. }
  18.  
  19. int main() {
  20.     stack <double> S; //a double type stack
  21.     double first, second;
  22.     string line, str;
  23.  
  24.     while(true) {
  25.         cout << "Enter the Reverse Polish Notation (as string): ";
  26.         getline(cin, line);
  27.  
  28.         if(line[0] == '%') exit(1);
  29.  
  30.         istringstream inpstr(line);
  31.  
  32.         while(inpstr >> str) {
  33.             if(str == "+") {//ADDITION +
  34.                 pop(first, second, S);
  35.                 S.push(first + second);
  36.             }
  37.  
  38.             else if(str == "-") {//SUBSTRACTION -
  39.                 pop(first, second, S);
  40.                 S.push(first - second);
  41.             }
  42.  
  43.             else if(str == "*") {//MULTIPLICATION *
  44.                 pop(first, second, S);
  45.                 S.push(first * second);
  46.             }
  47.  
  48.             else if(str == "/") {//DIVISION /
  49.                 pop(first, second, S);
  50.                 S.push(first / second);
  51.             }
  52.  
  53.             else if(str == "^") {//EXPONENT ^
  54.                 pop(first, second, S);
  55.                 S.push(pow(first, second));
  56.             }
  57.  
  58.             else
  59.                 S.push(strtof(str.c_str(), NULL)); //str.c_str() returns a C-String eqv of the String type object
  60.         }
  61.         cout << "Value of the expression is: " << S.top() << endl;
  62.         cout << "Enter '%' to stop" << endl << endl;
  63.     }
  64.  
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement