Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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