Search code examples
c++data-structuresstackpostfix-notationinfix-notation

Using Stacks In C++ for infix and postfix expressions


I'm writing a program that takes user input and uses stacks to convert an infix expression into a postfix expression based on precedence, with operands always going before operators. For example, if a user inputs:

(a+b*c)

then the program should display:

abc*+

so far, I have this:

#include <iostream>
#include <stack>
#include <string>


using namespace std;

int main()
{
    stack<char> s;
    char input;
    while (cin.get(input) && input != '\n')
        {
            if (isalnum(input))
                cout << input << "\n";
            else if (input == '(')
                s.push(input);
            else if (input == ')')
            {
        while (!s.empty() && s.top() != '(')
            {
            cout << s.top();
            s.pop();
        }
            if(!s.empty()) 
                    s.pop();
            else
                cout << "ERROR: No Matching ( \n";
        }
     else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?
     {
         char a = '*';
         char b = '/';
         char c = '+';
         char d = '-';
         bool prec (char a, char b, char c, char d);
             return ('*' > '/' > '+' > '-');
             s.push(input);
     }
         else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
             while (!s.empty()) 
          {
              cout << s.top();
          s.pop();
                  s.push(input);
          }
        }
    while (!s.empty())
    {
        cout << s.top();
        s.pop();
    }
}

Which compiles and runs but is not functioning as it should. When an expression like "ab" is input, the program will display "ab" as it should but if I input "a+b+c", then only "a" will be displayed. This means the program is not placing the operators into the stack to be displayed later on. What I need help with is modifying the program so that when an operator is input, it should be added onto the stack and then displayed based on it's precedence (*>/>+>-) after the operands, when the input is done.

I'm quite new to C++ and programming in general, so any suggestions would be great.


Solution

  • else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
    

    This does not do what you think it does. You need to do

    else if (input == '*'|| input == '/'|| input == '+'|| input == '-' && s.top() >= input)
    

    And this looks like an error too

    bool prec (char a, char b, char c, char d);
    

    That's the syntax for a function prototype. Are you sure this compiles?