Hi. So, my assignment is to convert an infix expression into a postfix one, and then evaluate it. I already completed the infix to postfix part. I have a small problem evaluating the postfix expression though. The expression deals with booleans, and allows the ! operator. I'm not sure how I'm supposed to evaluate this. I know that if you use it like this "!false" your answer is going to be true, and vice versa. But in some of the test cases that we were given, the ! was not always in front of true or false. Sometimes it comes before a set of parentheses and there's a test case where he has 3 of them in a row. Does anyone have any suggestions?? Thank you!
Test cases:
T evaluates to true
T&(F) evaluates to false
T & !F evaluates to true
!(F|T) evaluates to false
!F|T evaluates to true
T|F&F evaluates to true
T&!(F|T&T|F)|!!!(F&T&F) evaluates to true
my code seems a little messy and repetitive also...so if anybody has any suggestions as to how I could make it look nicer or less busy feel free to let me know!! Thanks!
int evaluate(const string& infix, string& postfix, bool& result)
// Evaluates a boolean expression
// Precondition: infix is an infix boolean expression consisting of
// the symbols T and F, the operators |, &, and !, and parentheses,
// with embedded blanks allowed for readability.
// Postcondition: If infix is a syntactically valid infix boolean
// expression, postfix is set to the postfix form of that
// expression, result is set to the value of the expression, and
// the function returns zero. If infix is a malformed expression,
// the return value is 1. (In that case, postfix may or may not be
// changed and but result must be unchanged.)
{
bool T = true;
bool F = false;
stack<bool> value;
postfix = "";
for(int r = 0; r < length; r++)
{
char c = postfix[r];
if (c == 'T' || c == 'F')
{
if (c == 'T')
value.push(T);
else if (c == 'F')
value.push(F);
}
else
{
switch (c)
{
case '!':
result = //this is where I don't know what kind of code to include. break;
case '&':
bool operand2 = value.top();
value.pop();
bool operand1 = value.top();
value.pop();
result = operand1 && operand2;
break;
case '|':
bool operand2 = value.top();
value.pop();
bool operand1 = value.top();
value.pop();
result = operand1 || operand2;
break;
}
value.push(result);
}
}
}