All pastes #886059 Raw Edit

km

public cpp v1 · immutable
#886059 ·published 2008-01-31 12:04 UTC
rendered paste body
#include <iostream>#include <stack>#include <string>#include <vector>#include <sstream>using namespace std;float processStack(stack<string> &s);bool isOperator(string str);template <class T>T fromString(string x){    T retval;    istringstream strin(x);    strin >> retval;    return retval;}template <class T>string toString(T x){    ostringstream strout;    strout << x;    return strout.str();}void prompt(){    cout << ">> ";}vector<string> split(string line, string separator){    vector<string> retval;    char * cstr, * p;    cstr = new char [line.size() + 1];    strcpy(cstr, line.c_str());    p = strtok(cstr, separator.c_str());    while (p != NULL) {        retval.push_back(p);        p = strtok(NULL, separator.c_str());    }    delete cstr;    return retval;}bool isOperator(string str){    string operators [] = {"+", "-", "*", "/"};    for (int i = 0; i < 4; i++) {        if (str == operators[i]) return true;    }    return false;}float processStack(stack<string> &s){    string str("");    if (!s.empty()) {        str = s.top(); s.pop();        if (!isOperator(str)) {            return fromString<int>(str);        }        else {            string stra = s.top();            float ia = 0.0;            if (isOperator(stra)) ia = processStack(s);            else {                ia = fromString<float>(stra);                s.pop();            }            string strb = s.top();            float ib = 0.0;            if (isOperator(strb)) ib = processStack(s);            else {                ib = fromString<float>(strb);                s.pop();            }            if (str == "+") {                return ia + ib;            }            else if (str == "-") {                return ia - ib;            }            else if (str == "*") {                return ia * ib;            }            else if (str == "/") {                return ia / ib;            }        }    }    return 0;}int main (int argc, char *argv[]){    stack<string> s;    char buff [8126];    prompt();    while (cin.good() && cin.getline(buff, 8126)) {        string line(buff);        if (line == "bye") return 0;        vector<string> tokens = split(line, " ");        for (size_t i = 0; i < tokens.size(); i++) {            s.push(tokens[i]);        }        cout << "result: " + toString<float>(processStack(s)) << endl;        prompt();    }    return 0;}