Created
October 22, 2015 08:59
-
-
Save stelf/1992c015a56384782680 to your computer and use it in GitHub Desktop.
tiny rpn calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// rpn.cpp : micro example of RPN calculator | |
// | |
#include "stdafx.h" | |
#include <stack> | |
#include <iostream> | |
using namespace std; | |
char * rpns[] = { | |
"14/2+", | |
"54*32++", | |
"546+/" | |
}; | |
int main () { | |
/* iterate over all input data */ | |
for (char*& str : rpns) { | |
stack<float> s; | |
for (char *c = str; *c; c++) { | |
/* as long as it is digit -> push it */ | |
if (*c >= '0' && *c <= '9') { | |
s.push(*c - '0'); | |
} | |
else { | |
/* mind that we first pop the second operand then the first */ | |
float b = s.top(); s.pop(); | |
float a = s.top(); s.pop(); | |
switch (*c) { | |
case '+': s.push(a + b); break; | |
case '-': s.push(a - b); break; | |
case '*': s.push(a * b); break; | |
case '/': s.push(a / b); break; | |
} | |
} | |
} | |
cout << str << " = " << s.top() << endl; | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment