c++ i made a postfix calculator that works. I am struggling with the exception c
ID: 3772307 • Letter: C
Question
c++ i made a postfix calculator that works. I am struggling with the exception cases. I need it them so an error pops up if the user inputs "1+2*", (1+2)) or "1/0" Thank you in advanced
Here is my code:
#include <iostream>
#include <stack>
using namespace std;
bool isOperator(char character) {
if (character == '+' || character == '-' || character == '*' || character == '/') {
return true;
}
return false;
}
bool isOperand(char character) {
if (!isOperator(character) && character != '(' && character != ')') {
return true;
}
return false;
}
int compareOperators(char op1, char op2) {
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) { return -1; }
else if ((op1 == '+' || op1 == '-') && (op2 == '*' || op2 == '/')) { return 1; }
return 0;
}
int main(){
stack<char> opStack;
string postFixString = "";
char input[100];
cout << "Enter an expression: ";
cin >> input;
char *cPtr = input;
while (*cPtr != '') {
if (isOperand(*cPtr)) { postFixString += *cPtr; }
else if (isOperator(*cPtr)) {
while (!opStack.empty() && opStack.top() != '(' && compareOperators(opStack.top(),*cPtr) <= 0) {
postFixString += opStack.top();
opStack.pop();
}
opStack.push(*cPtr);
}
else if (*cPtr == '(') { opStack.push(*cPtr); }
else if (*cPtr == ')') {
while (!opStack.empty()) {
if (opStack.top() == '(') { opStack.pop(); break; }
postFixString += opStack.top();
opStack.pop();
}
}
cPtr++;
}
while (!opStack.empty()) {
postFixString += opStack.top();
opStack.pop();
}
cout << "Postfix is: " << postFixString << endl;
int size = sizeof(postFixString);
int i;
int op1,op2;
char first;
stack<char> reverse;
stack<int> calculate;
for(i=postFixString.size()-1;i>=0;i--)
reverse.push(postFixString[i]);
while(!reverse.empty())
{
first = reverse.top();
if(isOperator(first))
{
op1 = calculate.top();
calculate.pop();
op2 = calculate.top();
calculate.pop();
if(first == '+')
calculate.push(op1+op2);
if(first == '-')
calculate.push(op1-op2);
if(first == '*')
calculate.push(op1*op2);
if(first == '/')
calculate.push(op1/op2);
}else{
calculate.push(first-'0');
}
reverse.pop();
}
cout << calculate.top()<< endl;
return 0;
}
Explanation / Answer
To validate wether the given expression is balanced and complete or not, i have added a method isBalaced().
isBalaced() returns true if the expression is balanced and complete. otherwise, the code asks the user to enter expression.
bool isBalanced(char *pt)
{
int brktsBalanced=0;
bool operBalanced=true;
while(*pt!='')
{
if(isOperand(*pt))
{
if(operBalanced==false)
operBalanced=true;
}
else if(isOperator(*pt))
{
operBalanced=false;
}
else if(*pt=='(')
{
brktsBalanced++;
}
else if(*pt==')')
{
brktsBalanced--;
}
pt++;
}
if(brktsBalanced==0 && operBalanced==true)
return true;
else
return false;
}
Program:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.