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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#include <iostream>
#include <string.h>
#include <stack>
#include <sstream>
#include <stdlib.h>
#include "Stack.h"
using namespace std;
#define _DEBUG
#ifdef _DEBUG
#define TRACE(...) { printf(__VA_ARGS__); }
#else
#define TRACE(...)
#endif
int main ()
{
cout << "Welcome to my postfix notation calculator. \n";
int i, num, result, topNum, secondNum, catchVar;
char op, ch;
string str, str1;
IntStack stack;
getline (cin, str);
istringstream is (str);
// read code , adding it to stack and preforming operations when an operator is reached
for (; is >> str1;)
{
TRACE("Reading %s\n", str1.c_str());
if (str1 == "+")
{
topNum = atoi (str1.c_str ());
TRACE("topNum = %d\n", topNum);
stack.pop (catchVar);
TRACE("Popping catchVar=%d\n",catchVar);
secondNum = atoi (str1.c_str ());
TRACE("secondNum = %d\n", secondNum);
stack.pop (catchVar);
TRACE("Popping catchVar=%d\n",catchVar);
stack.push (topNum + secondNum);
TRACE("Pushed %d to stack\n", topNum + secondNum);
}
else if (str1 == "-")
{
topNum = atoi (str1.c_str ());
stack.pop (catchVar);
secondNum = atoi (str1.c_str ());
stack.pop (catchVar);
stack.push (secondNum - topNum);
}
else if (str1 == "*")
{
topNum = atoi (str1.c_str ());
stack.pop (catchVar);
secondNum = atoi (str1.c_str ());
stack.pop (catchVar);
stack.push (topNum * secondNum);
}
else if (str1 == "/")
{
topNum = atoi (str1.c_str ());
stack.pop (catchVar);
secondNum = atoi (str1.c_str ());
stack.pop (catchVar);
stack.push (secondNum / topNum);
}
// if there was no operator push the number onto the stack
else
{
stack.push (strtof (str1.c_str (), NULL));
TRACE("Pushed %d to stack\n", strtof (str1.c_str (), NULL));
cout << str1 << '\n';
}
}
stack.pop (catchVar);
cout << "The answer is:" << catchVar;
system ("pause");
return 0;
}
| |