Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stack>
- using namespace std;
- string postfixC(string infix)
- {
- string output = "";
- stack<char> operators;
- for (int i = 0; i < infix.length(); i++)
- {
- if (infix[i] == 't' || infix[i] == 'f')
- {
- output += infix[i];
- }
- else if (infix[i] == '(')
- {
- operators.push(infix[i]);
- }
- else if (infix[i] == ')')
- {
- while (operators.top() != '(')
- {
- output += operators.top();
- operators.pop();
- }
- operators.pop();
- }
- else if (infix[i] == '!')
- {
- operators.push(infix[i]);
- }
- else if (infix[i] == '*')
- {
- while (!operators.empty() && (operators.top() == '*' || operators.top() == '!'))
- {
- output += operators.top();
- operators.pop();
- }
- operators.push(infix[i]);
- }
- else if (infix[i] == '+')
- {
- while (!operators.empty() && (operators.top() == '*' || operators.top() == '!' || operators.top() == '+'))
- {
- output += operators.top();
- operators.pop();
- }
- operators.push(infix[i]);
- }
- }
- while (!operators.empty())
- {
- output += operators.top();
- operators.pop();
- }
- return output;
- }
- bool calculatePostfix(string postfix)
- {
- stack<char> st;
- for (int i = 0; i < postfix.length(); i++)
- {
- if (postfix[i] == 't' || postfix[i] == 'f')
- {
- st.push(postfix[i]);
- }
- else if (postfix[i] == '*')
- {
- bool operandB = (st.top() == 't') ? true : false;
- st.pop();
- bool operandA = (st.top() == 't') ? true : false;
- st.pop();
- if (operandA && operandB)
- {
- st.push('t');
- }
- else
- {
- st.push('f');
- }
- }
- else if (postfix[i] == '+')
- {
- bool operandB = (st.top() == 't') ? true : false;
- st.pop();
- bool operandA = (st.top() == 't') ? true : false;
- st.pop();
- if (operandA || operandB)
- {
- st.push('t');
- }
- else
- {
- st.push('f');
- }
- }
- else if (postfix[i] == '!')
- {
- bool operand = (st.top() == 't') ? true : false;
- st.pop();
- if (!operand)
- {
- st.push('t');
- }
- else
- {
- st.push('f');
- }
- }
- }
- return (st.top() == 't');
- }
- int main()
- {
- string expr;
- cout << "Enter expression: ";
- getline(cin, expr);
- if (calculatePostfix(postfixC(expr)))
- {
- cout << 't' << endl;
- }
- else
- {
- cout << 'f' << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement