conversion from infix to postfix

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Nhd
    New Member
    • Aug 2006
    • 24

    conversion from infix to postfix

    Hi... I need a program to convert an infix arithmetic expression to postfix with the use of stacks... Can anyone tell me how do i go about implementing this? thanks
  • D_C
    Contributor
    • Jun 2006
    • 293

    #2
    There is a standard algorithm to do this. The last paragraph of this website has the steps.

    Print the numbers out in normal order, push parenthesis and operators onto the stack. When parenthesis line up, ignore them, don't print anything. If they don't line up, that's an error. Then, depending upon priority of the operator (PEMDAS) push or pop the operator off the stack. If you pop it, display it in the output.

    The website explains it better, why don't you go have a look.

    Comment

    • Nhd
      New Member
      • Aug 2006
      • 24

      #3
      Hi can anyone help me to check this... Im lost in my own program... I noe some part of it is wrong... can anyone tell me... thanks

      #include <iostream>
      #include <stack>
      #include <vector>
      #include <sstream>
      using namespace std;

      int main()
      {
      string line, str;
      int number;

      cout<<"Sample Input 1"<<" "<<endl;
      cin>>line;

      getline(cin, line);
      istringstream iss(line); //create string stream

      while(!iss.eof( ))
      {
      iss >> str; //reads from iss into str until next space is met
      }

      //Postfix evaluation
      int eval_postfix(co nst vector<char>&v, stack<int>&st)
      {
      for (vector<char>:: const_iterator str = v.begin(begin() ; str !=v.end(); ++str)
      {
      if ('0'<= str && str<='9')
      st.push(str-'0')
      else
      {
      int arg2 = st.top();
      st.pop();
      int arg1 = st.top();
      st.pop();
      int result;

      if (str == "+" || str == "-") //when you compare for char, it's '+' and '-'
      {
      case '+': result = arg1 + arg2;
      return 1;
      break;
      case '-': result = arg1 - arg2;
      resturn 2;
      break;
      }
      else if (str == "*" || str == "/")
      {
      case '*': result = arg1 * arg2;
      break;
      return 3;
      case '/': result = arg1 / arg2;
      break;
      return 4;
      } //end if else

      st.push(result) ;
      } //end else
      }//end for

      int i = st.top();
      st.pop();
      return i;
      }//end eval_postfix


      system("pause") ;
      return 0;
      }

      Comment

      • Nhd
        New Member
        • Aug 2006
        • 24

        #4
        Hi i modify my codes but i'm unable to execute it.... can anyone help me to spot the mistake.. thanks

        Code:
        #include <iostream>
        #include <stack>
        #include <vector>
        #include <sstream>
        using namespace std;
        
        int main()
        {
              string line, str;  
              int number;
              
              cout<<"Sample Input:"<<" "<<endl;
              cin>>line;
              
              getline(cin, line);
              istringstream iss(line); //create string stream
              
              while(!iss.eof()) 
              {
                   iss >> str; //reads from iss into str until next space is met
              }
              
              //Code of Postfix Evaluation
              int eval_postfix(const vector<char>&v, stack<int>&st)
              {
                  for (vector<char>::const_iterator ptr = v.begin(begin(); ptr !=v.end(); ++ptr)
                  {
                      if ('0'<= *ptr && *ptr<='9')
                      st.push(*ptr-'0')
                      else
                      {
                          int arg2 = st.top();
                          st.pop();
                          int arg1 = st.top();
                          st.pop();
                          int result;
                          
                      switch (*ptr)
                      {
                             case '+': result = arg1 + arg2;
                             break;
                             case '-': result = arg1 - arg2;
                             break;
                             case '*': result = arg1 * arg2;
                             break;
                             case '/': result = arg1 / arg2;
                             break; 
                      } //end switch
                      st.push(result);
                      } //end else
                  }//end for
                  
                  int i = st.top();
                  st.pop();
                  return i;
              }//end eval_postfix 
        
               cout<<i<<"Sample Output:"<<" "<<endl;
                     
               system("pause");
               return 0;
        }
        Last edited by Banfa; Sep 20 '06, 09:03 AM. Reason: Added [code]...[/code] round the code

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          You have tried to define the function

          int eval_postfix(co nst vector<char>&v, stack<int>&st)

          inside the function

          int main()

          This is not allowed in C/C++ move the definition of the function eval_postfix outside the function main.

          Comment

          • Nhd
            New Member
            • Aug 2006
            • 24

            #6
            Hi... I put the "int eval_postfix(co nst vector<char>&v, stack<int>&st)" out of the main, i still get error.. the error i get is something to do with this "int main()".. but i cant remove the "int main()"..... I'm sory to bother u but im really weak in my programming...

            #include <iostream>
            #include <stack>
            #include <vector>
            #include <sstream>
            using namespace std;
            int eval_postfix(co nst vector<char>&v, stack<int>&st)
            int main()
            {
            string line, str;
            int number;
            char *cstr;

            cout<<"Sample Input:"<<" "<<endl;
            cin>>line;

            getline(cin, line);
            istringstream iss(line); //create string stream

            while(!iss.eof( ))
            {
            iss >> str; //reads from iss into str until next space is met
            }

            //Code of Postfix Evaluation
            for (vector<char>:: const_iterator ptr = v.begin(begin() ; ptr !=v.end(); ++ptr)
            {
            if ('0'<= *ptr && *ptr<='9')
            st.push(*ptr-'0')
            else
            {
            int arg2 = st.top();
            st.pop();
            int arg1 = st.top();
            st.pop();
            int result;

            switch (*ptr)
            {
            case '+': result = arg1 + arg2;
            break;
            case '-': result = arg1 - arg2;
            break;
            case '*': result = arg1 * arg2;
            break;
            case '/': result = arg1 / arg2;
            break;
            } //end switch
            st.push(result) ;
            } //end else
            }//end for

            int i = st.top();
            st.pop();
            return i;
            }//end eval_postfix

            //convert string to integer
            number = atoi(str.c_str( )); //now number is 1234

            //convert integer into string
            sprintf(cstr, "%d", number); //print number into cstring
            string str(cstr); //makes cstring a string

            //checking if all characters of the string are digits
            cstr = str.c_str();
            if ( isdigit(*cstr) ) //checks the first character of cstr is digit or not
            return true;

            cout<<"Sample Output:"<<cin<< " "<<endl;

            system("pause") ;
            return 0;
            }

            Comment

            • Banfa
              Recognized Expert Expert
              • Feb 2006
              • 9067

              #7
              You have to move the entire function, not just the header line

              This
              Code:
              int main()
              {
                // main code
              
                int fn()
                {
                  // function code
                }
              
                // more main code
              }
              becomes

              Code:
              int fn();
              
              int main()
              {
                // main code
              
                // more main code
              }
              
              int fn()
              {
                // function code
              }

              Comment

              • Nhd
                New Member
                • Aug 2006
                • 24

                #8
                for this function, for the 2nd sentence , may i noe how do i declare "begin"? i hav error regarding this.... should i declare it in main function or in its own function itself...

                int eval_postfix(co nst vector<char>&v, stack<int>&st)
                {
                for (vector<char>:: const_iterator ptr = v.begin(begin() ; ptr !=v.end(); ++ptr)
                {
                if ('0'<= *ptr && *ptr<='9')
                st.push(*ptr-'0');
                else
                {
                int arg2 = st.top();
                st.pop();
                int arg1 = st.top();
                st.pop();
                int result;

                switch (*ptr)
                {
                case '+': result = arg1 + arg2;
                break;
                case '-': result = arg1 - arg2;
                break;
                case '*': result = arg1 * arg2;
                break;
                case '/': result = arg1 / arg2;
                break;
                } //end switch
                st.push(result) ;
                } //end else
                }//end for

                int i = st.top();
                st.pop();
                return i;
                }//end eval_postfix

                Comment

                • Banfa
                  Recognized Expert Expert
                  • Feb 2006
                  • 9067

                  #9
                  Not really sure what you are saying but

                  for (vector<char>:: const_iterator ptr = v.begin(begin() ; ptr !=v.end(); ++ptr)

                  should be

                  for (vector<char>:: const_iterator ptr = v.begin(); ptr !=v.end(); ++ptr)

                  Comment

                  • Nhd
                    New Member
                    • Aug 2006
                    • 24

                    #10
                    Thanks Banfa for ur help.... but do u mind helping me to check my program please.... I've been struggling from juz now and i still cant do it....

                    Code:
                    #include <iostream>
                    #include <stack>
                    #include <vector>
                    #include <sstream>
                    using namespace std;
                    
                    int eval_postfix(const vector<char>&v, stack<int>&st);
                    int main()
                    {
                          string line, str;
                          int number;
                          char *cstr;
                          
                          cout<<"Sample Input:"<<" "<<endl;
                          cin>>line;
                          
                          getline(cin, line);
                          istringstream iss(line); //create string stream
                          
                          while(!iss.eof()) 
                          {
                           iss >> str; //reads from iss into str until next space is met
                          }
                          
                          //convert string to integer
                          number = atoi(str.c_str()); //now number is 1234
                          
                          cout<<"Sample Output:"<<str<<" "<<endl;
                                 
                          system("pause");
                          return 0;
                    }
                    	         
                         //Code of Postfix Evaluation
                          int eval_postfix(const vector<char>&v, stack<int>&st)
                          {
                              for (vector<char>::const_iterator ptr = v.begin(); ptr !=v.end(); ++ptr)
                              {
                                  if ('0'<= *ptr && *ptr<='9')
                                  st.push(*ptr-'0');
                                  else
                                  {
                                      int arg2 = st.top();
                                      st.pop();
                                      int arg1 = st.top();
                                      st.pop();
                                      int result;
                                      
                                  switch (*ptr)
                                  {
                                         case '+': result = arg1 + arg2;
                                         break;
                                         case '-': result = arg1 - arg2;
                                         break;
                                         case '*': result = arg1 * arg2;
                                         break;
                                         case '/': result = arg1 / arg2;
                                         break; 
                                  } //end switch
                                  st.push(result);
                                  } //end else
                              }//end for
                              
                              int i = st.top();
                              st.pop();
                              return i;
                          }//end eval_postfix 
                     
                          //Conversion from Infix to Postfix expression
                          vector<char> postFix;
                          for (vector<char>::const_iterator ptr = v.begin(); ptr !=v.end(); ++ptr)
                          {
                            switch(ch)
                            {
                                      case operand: 
                                           postfixExp = postfixExp + ch;
                                           break;
                                      case '(': 
                                           Stack.push (ch);
                                           Break;
                                      case ')':
                                           while (stack.top()!='(')
                                           {
                                                 postfixExp = postfixExp + stack.top();
                                                 Stack.pop();
                                           } //end while
                                           
                                           Stack.pop();
                                           break;
                                           
                                      //infix to postfix - use stack for storing operators
                                      case operator:
                                           
                                           while (!Stack.isEmpty() && Stack.top != '(' && precedence(ch) >= precedence(stack.top()))
                                           {
                                                 postfixExp = postfixExp + Stack.top();
                                                 Stack.pop();
                                            } end while
                                 }//end switch
                        
                        } //end for
                        
                        while (!Stack.isEmpty())
                        {
                              postfixExp = postfixExp + Stack.top();
                              Stack.pop()
                        }// end while
                    Last edited by Banfa; Sep 20 '06, 05:10 PM. Reason: Added [code]...[/code] round the code

                    Comment

                    • Banfa
                      Recognized Expert Expert
                      • Feb 2006
                      • 9067

                      #11
                      None of this code

                      Code:
                            //Conversion from Infix to Postfix expression
                            vector<char> postFix;
                            for (vector<char>::const_iterator ptr = v.begin(); ptr !=v.end(); ++ptr)
                            {
                              switch(ch)
                              {
                                        case operand: 
                                             postfixExp = postfixExp + ch;
                                             break;
                                        case '(': 
                                             Stack.push (ch);
                                             Break;
                                        case ')':
                                             while (stack.top()!='(')
                                             {
                                                   postfixExp = postfixExp + stack.top();
                                                   Stack.pop();
                                             } //end while
                                             
                                             Stack.pop();
                                             break;
                                             
                                        //infix to postfix - use stack for storing operators
                                        case operator:
                                             
                                             while (!Stack.isEmpty() && Stack.top != '(' && precedence(ch) >= precedence(stack.top()))
                                             {
                                                   postfixExp = postfixExp + Stack.top();
                                                   Stack.pop();
                                              } end while
                                   }//end switch
                          
                          } //end for
                          
                          while (!Stack.isEmpty())
                          {
                                postfixExp = postfixExp + Stack.top();
                                Stack.pop()
                          }// end while
                      Is inside a function and is causing a syntax error

                      It doesn't appear to have any purpose so I guess you can just delete it as the program compiles fine without it.

                      Comment

                      • Nhd
                        New Member
                        • Aug 2006
                        • 24

                        #12
                        hi Banfa.. my purpose in typing out those codes is to convert infix to postfix..

                        for example:
                        Sample input 1
                        1 + 2 * 3 - 4 / 2 + 5 * 6
                        Sample output 1
                        35

                        Sample input 2
                        ( 10 + 20 ) * 30 - 4000 / 20 + 50 * 60
                        Sample output 2
                        3700

                        I'm trying to write a program for this... and my notes shows only these codes, the one that i type out...

                        what should i do now... :(

                        Comment

                        Working...