Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Evaluate the Value of a Reversed Polish Notation String
- #include <iostream>
- #include <stack>
- #include <sstream>
- #include <cstdlib>
- #include <cmath>
- using namespace std ;
- void pop(double &first, double &second, stack <double> &S) {
- second = S.top();
- S.pop();
- first = S.top();
- S.pop();
- }
- int main() {
- stack <double> S; //a double type stack
- double first, second;
- string line, str;
- while(true) {
- cout << "Enter the Reverse Polish Notation (as string): ";
- getline(cin, line);
- if(line[0] == '%') exit(1);
- istringstream inpstr(line);
- while(inpstr >> str) {
- if(str == "+") {//ADDITION +
- pop(first, second, S);
- S.push(first + second);
- }
- else if(str == "-") {//SUBSTRACTION -
- pop(first, second, S);
- S.push(first - second);
- }
- else if(str == "*") {//MULTIPLICATION *
- pop(first, second, S);
- S.push(first * second);
- }
- else if(str == "/") {//DIVISION /
- pop(first, second, S);
- S.push(first / second);
- }
- else if(str == "^") {//EXPONENT ^
- pop(first, second, S);
- S.push(pow(first, second));
- }
- else
- S.push(strtof(str.c_str(), NULL)); //str.c_str() returns a C-String eqv of the String type object
- }
- cout << "Value of the expression is: " << S.top() << endl;
- cout << "Enter '%' to stop" << endl << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement