Skip to content

Instantly share code, notes, and snippets.

@unvBell
Last active August 29, 2015 14:24
Show Gist options
  • Save unvBell/c99f9baba15320a72d26 to your computer and use it in GitHub Desktop.
Save unvBell/c99f9baba15320a72d26 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
#include <map>
#include <cassert>
#include <cstdlib>
using namespace std;
#define ERR err(__LINE__)
map<char, int> priority = {
{ '\0', -256 },
{ '(', -1 },
{ ')', -1 },
{ '+', 1 },
{ '-', 1 },
{ '*', 2 },
{ '/', 2 },
};
stack<char> op;
stack<double> num;
void err(int line) {
cout << "error at line " << line << endl;
assert(0);
}
double popNum() {
double a = num.top();
num.pop();
return a;
}
void popOp() {
char c = op.top();
if(c == '\0')
ERR;
if(c != '(') {
cout << c << ' ';
double b = popNum();
double a = popNum();
if(c == '+') { num.push(a+b); }
if(c == '-') { num.push(a-b); }
if(c == '*') { num.push(a*b); }
if(c == '/') { num.push(a/b); }
}
op.pop();
}
int main() {
cout << '>';
op.push('\0');
while(true) {
string input;
cin >> input;
if(input == "end") {
while(op.top() != '\0')
popOp();
break;
}
if(isdigit(input[0])) {
num.push(atof(input.c_str()));
cout << num.top() << ' ';
}
else {
char c = input[0];
if(c == '(') {
op.push(c);
}
else if(c == ')') {
if(op.top() == '(')
ERR;
while(op.top() != '(')
popOp();
popOp();
}
else {
while(priority[c] <= priority[op.top()])
popOp();
op.push(c);
}
}
}
cout << endl << num.top() << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment