View Full Version: RPN Calc.

C++ Learning Community > C++ Creations > RPN Calc.


Title: RPN Calc.
Description: STL-oriented.


ramirez - June 23, 2005 12:47 PM (GMT)
I was bored so I attempted to write a Reverse Polish Calculator utilising STL, so here's the result.
I was lazy so it doesn't really do error checking, use CTRL+C to quit.
CODE
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <stack>
#include <map>
#include <algorithm>
using namespace std;

typedef double (*Op)(double, double);
typedef map<string, Op> OpTable;

double AddOp(double lhs, double rhs) { return lhs + rhs; }
double SubOp(double lhs, double rhs) { return lhs - rhs; }
double MulOp(double lhs, double rhs) { return lhs * rhs; }
double DivOp(double lhs, double rhs) { return lhs / rhs; }

OpTable ops;
stack <double> rpn;

void ParseToken(string token) {
   // Check if token exists in ops map
   OpTable::iterator op = ops.find(token);

   // If token is op
   if (op != ops.end()) {
       // Pop lhs & rhs values from stack
       double rhs = rpn.top(); rpn.pop();
       double lhs = rpn.top(); rpn.pop();
       // Push new value onto the stack
       rpn.push(op->second(lhs, rhs));
   }
   // If token is a number
   else {
       double num;
       istringstream strnum(token);
       strnum >> num;
       rpn.push(num);
   }
}

int main(int argc, char * argv[])
{
   // Define vars
   string input;
   vector<string> tokens;

   // Build ops table
   ops["+"] = &AddOp;
   ops["-"] = &SubOp;
   ops["*"] = &MulOp;
   ops["/"] = &DivOp;

   for(;;) {
       // Get & validate input
       getline(cin, input);
       if (cin.fail())
           break;

       // Tokenize
       tokens.clear();
       istringstream inputstream(input);
       copy(istream_iterator<string>(inputstream), istream_iterator<string>(), back_inserter(tokens));
       for_each(tokens.begin(), tokens.end(), ParseToken);

       // Output result & pop result from stack
       cout << "\t" << rpn.top() << endl;
       rpn.pop();
   }

   return 0;
}

donprogc++ - June 23, 2005 04:46 PM (GMT)
Good Job B)




* Hosted for free by InvisionFree