#include <iostream>
#include <cstdio>
#include <cctype>
#include <cstdlib>
#include "stack.h"
using namespace std;
int main()
{
//variables declaration
Stack S;
int num;
int op1,op2;
int c;
cout <<"Welcome to Reverse Polish Notation calculator (RPN)\n";
cout << "-------------------------------------------\n";
cout << "please enter the number and the math symbol using the following format\n";
cout << " X_Y_+ (or-, *, /)\n";
cout << " e\n\n";
cout << "Warn: each input is seperated by a 'space'\n";
cout << "-------------------------------------------\n";
cout << "Direction for commands:";
cout << "press 'e' to print out the result\n";
cout << " press 'd' to reset the stack\n";
cout << " press 'q' to print out the result and exit\n";
while((c=getchar()) != EOF)
{
if(isdigit(c))//ask user to input the stack one by one
{
ungetc(c, stdin);
scanf("%d", &num);
S.push(num);
}
else
{
switch(c)//different cases of operations
{
case '+':
S.push(S.pop() + S.pop());
break;
case '-':
op2 = S.pop();
op1 = S.pop();
S.push(op1 - op2);
break;
case '*':
S.push(S.pop() * S.pop());
break;
case '/':
op2 = S.pop();
op1 = S.pop();
if(op2 == 0)
{
cerr << "Error: divided by zero!" << endl;
exit(1);
}
S.push(op1 / op2);
break;
case 'e'://different cases for execution
cout << "result: " << S.pop() << endl;
break;
case 'd':
while(!S.empty())
S.pop();
break;
case 'q':
cout << "result: " << S.pop() << endl;
return 0;
break;
}
}
}
return 0;
}
RPN.rar_RPN calculator
版权申诉
142 浏览量
2022-09-22
21:42:44
上传
评论
收藏 2KB RAR 举报
小波思基
- 粉丝: 72
- 资源: 1万+