1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
#include <stack>
#include <iostream>
#include "calc_useful.h"
using namespace std;
int main()
{
while(true)
{
// declare your stack here
stack<int> stk;
char c;
int onenum, twonum;
cout<<"Please enter your expression:\n";
c = cin.get();
while(c != '\n')
{
if(isdigit(c))
{
cin.putback(c);
cin>>onenum;
stk.push(onenum);
// stack operation here.
}
else if(isop(c))
{
// if the stack is empty you will get a error.
if(stk.empty())
{
cout<<"Wrong Expression!"<<endl;
return 0;
}
twonum = stk.top();
stk.pop();
if(stk.empty())
{
cout<<"Wrong Expression!"<<endl;
return 0;
}
onenum = stk.top();
stk.pop();
onenum = evaluate(onenum,twonum,c);
stk.push(onenum);
// here is where you have to pop a couple of numbers,
// apply the operator to the numbers
// and then push the result back into the stack
}
c = cin.get(); // reading at the bottom of the sentinel loop
}
// this is where you get your final answer off the stack
// it should be the only number left on the stack at this point
if(stk.empty())
{
cout<<"Wrong Expression!"<<endl;
return 0;
}
onenum = stk.top();
stk.pop();
if(!stk.empty())
{
cout<<"Error. Insufficient operators for operands.\n";
return -1;
}
cout<<"The answer is: "<< onenum<<endl;
}
}
cu.c
|
bool isop(char op){
return op =='+' || op == '-' || op == '*' || op == '/';
}
int evaluate(int num1, int num2, char op){
if(op == '+') return num1 + num2;
if(op == '-') return num1-num2;
if(op == '*') return num1*num2;
if(op == '/') return num1/num2;
else return 0;
}
double evaluate(double num1, double num2, char op){
if(op == '+') return num1 + num2;
if(op == '-') return num1-num2;
if(op == '*') return num1*num2;
if(op == '/') return num1/num2;
else return 0;
}
cu.h---------------------------
double evaluate(double num1, double num2, char op);
int evaluate(int num1, int num2, char op);
bool isop(char op);
|