Oct 25, 2015 at 11:15pm UTC
Write a program in C++ to evaluate boolean expressions. The input expressions for this program will use the operations &&, ||, and ! (the "not" operation.) The input expression will combine simple boolean comparisons of numbers such as (1 <2) and (6 < 3). Allow the following comparison operations: <, >, <=, >=, == and !=. Be sure to note that "not" is a unary operation. You can assume that the argument to "not" (which follows the !) is enclosed in parentheses.
Please help here is my code:
bool read_and_evaluate(istream& ins)
// Library facilities used: cstring, iostream, stack
{
const char DECIMAL = '.';
const char RIGHT_PARENTHESIS = ')';
stack<int> numbers;
stack<char> operations;
int number;
char symbol;
// Loop continues while istream is not �bad� (tested by ins) and next character isn�t newline.
while (ins && ins.peek( ) != '\n')
{
if (isdigit(ins.peek( )) || (ins.peek( ) == DECIMAL))
{
ins >> number;
numbers.push(number);
}
else if (strchr("&&||!", ins.peek( )) != NULL)
{
ins >> symbol;
operations.push(symbol);
}
else if (ins.peek( ) == RIGHT_PARENTHESIS)
{
ins.ignore( );
evaluate_stack_tops(numbers, operations);
}
else
ins.ignore( );
}
return numbers.top( );
}
void evaluate_stack_tops(stack<int>& numbers, stack<char>& operations)
// Library facilities used: stack
{
int operand1, operand2;
bool bool1, bool2;
operand2 = numbers.top( );
numbers.pop( );
operand1 = numbers.top( );
numbers.pop( );
switch (operations.top( ))
{
case '<': numbers.push(operand1 < operand2);
break;
case '>': numbers.push(operand1 > operand2);
break;
case '<=': numbers.push(operand1 <= operand2);
break;
case '>=': numbers.push(operand1 >= operand2);
break;
case '==': numbers.push(operand1 == operand2);
break;
case '!=': numbers.push(operand1 != operand2);
break;
}
operations.pop( );
}
Oct 26, 2015 at 11:22am UTC
Note that many of the operators consist of two characters so they can't be stored in a single char.