Skip to content

Instantly share code, notes, and snippets.

@nkapliev
Created September 9, 2016 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkapliev/4a41806475895262b59becafde6cc606 to your computer and use it in GitHub Desktop.
Save nkapliev/4a41806475895262b59becafde6cc606 to your computer and use it in GitHub Desktop.
Polish notation calculator on C++. @see https://en.wikipedia.org/wiki/Polish_notation
#include <iostream>
#include <stdio.h>
using namespace std;
class cStack
{
private:
int A[255];
int ptr;
public:
cStack(){
ptr = 0;
}
void push(int & b){
A[ptr] = b;
ptr+=1;
}
int pop(){
ptr-=1;
return A[ptr];
}
};
void add(cStack & tStack){
int a, b, c;
a = tStack.pop();
b = tStack.pop();
c = a + b;
tStack.push(c);
}
void sub(cStack & tStack){
int a, b, c;
a = tStack.pop();
b = tStack.pop();
c = b - a;
tStack.push(c);
}
void mul(cStack & tStack){
int a, b, c;
a = tStack.pop();
b = tStack.pop();
c = a * b;
tStack.push(c);
}
int main()
{
cStack stack;
char c;
char str[255]={0};
int i=0;
int temp;
//cin>>noskipws;
while(cin>>c) // Цикл пока считывание успешно
{
str[i] = c;
i+=1;
}
i=0;
while(str[i]!=0)
{
if (str[i]=='+'){
add(stack);
}
else if (str[i]=='-'){
sub(stack);
}
else if (str[i]=='*'){
mul(stack);
}
else {
temp = (int)str[i] - 48;
stack.push(temp);
}
i+=1;
}
cout << stack.pop();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment