// L-15 MCS 360 Mon 27 Sep 2010 : converting_infix_sum.cpp

/* This program takes an infix sum "4 + 8 - 2 + 12" and converts it
   into postfix notation "4 8 + 2 - 12 +".

Because + and - have the same precedence, we need to store only the
previous operator each time we encounter an operand.

The program assumes the infix notation for the expression is valid. */

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
   string expression;

   cout << "Give an infix sum : ";
   getline(cin,expression,'\n');
   cout << "-> your expression : \""
        << expression << "\"" << endl;

   istringstream arguments(expression);
   char next_character;
   char previous_op = ' ';
   ostringstream postfix_expression;

   while(arguments >> next_character)
   {
      if(!isdigit(next_character))  // assume + or -
      {
         if(previous_op != ' ')
            postfix_expression << previous_op << " ";
         previous_op = next_character;
      }
      else
      {
         arguments.putback(next_character);
         int value;
         arguments >> value;
         postfix_expression << value << " ";
      }
   }
   postfix_expression << previous_op;
   cout << "postfix notation of \"" << expression
        << "\" is \"" << postfix_expression.str()
        << "\"" << endl;

   return 0;
}

