stack in C++
-
SAn schrieb:
Hey, people!
...Hi.
Ah nice to know. I googled it, but i couldn't find anything good about a "stack-rechner".
And I think the OP also didn't know it clear enough to explain us the situation.But it's not a problem to change the calculator to this functionability.
-
Here is the solution I wrote in 20 minutes (without any error checking and so on):
#include <iostream> #include <string> #include <sstream> #include <stack> using namespace std; typedef stack<double> TStack; inline double Pop(TStack& Stack) { double result(Stack.top()); Stack.pop(); return result; } inline double StringToDouble(string const &String) { istringstream Stream(String); double result; Stream>>result; return result; } int main(int argc, char **argv) { TStack Stack; string Input; while(true) { cin>>Input; if(Input[0]=='.') break; switch(Input[0]) { case '+': Stack.push(Pop(Stack)+Pop(Stack) ); break; case '-': Stack.push(-Pop(Stack)+Pop(Stack) ); break; case '/': Stack.push(1.0/Pop(Stack)*Pop(Stack)); break; case '*': Stack.push(Pop(Stack)*Pop(Stack) ); break; default: Stack.push(StringToDouble(Input)); } cout<<"Result: "<<Stack.top()<<endl; }; cout<<"Done"<<endl; return EXIT_SUCCESS; }Here is the result:
2 Result: 2 3 Result: 3 + Result: 5 4 Result: 4 5 Result: 5 + Result: 9 * Result: 45 . DoneYou can also enter input in one line using spaces:
2 3 + 4 5 + * . Result: 2 Result: 3 Result: 5 Result: 4 Result: 5 Result: 9 Result: 45 Done
-
SAn schrieb:
2 3 + 4 5 + *
Hi Brother !
Thats RPN (Reverse Polish Notation by Jan Lukasiewicz) isnt it ?
I wrote such a calculator/parser last year^^
-
Big Brother schrieb:
Hi Brother !
Thats RPN (Reverse Polish Notation by Jan Lukasiewicz) isnt it ?
I wrote such a calculator/parser last year^^
Yes, that is RPN. And the "stack computer" is the simple parser which can process RPN.