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

/* A postfix expression with single digit natural operands is
   for example in the string "10 2 * 5 / 6 2 5 * +  -"
   and in this program we process a postfix string.

We illustrate how we can read from a string using istringstream. */

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

using namespace std;

int main()
{
   string expression;

   cout << "Give a postfix expression : ";
   getline(cin,expression,'\n');
   cout << "-> your expression : \""
        << expression << "\"" << endl;

   istringstream tokens(expression);
   char next_character;
   cout << "-> your expression : \"";
   while(tokens >> next_character)
      cout << next_character;
   cout << "\"" << endl;

   const string operators = "+-*/";
   istringstream arguments(expression);
   bool valid = true;
   cout << "-> parsing expression ...\n";
   while(arguments >> next_character)
   {
      if(!isdigit(next_character))
      {
         if(operators.find(next_character) == string::npos)
         {
            cout << next_character
                 << " is invalid operator" << endl;
            valid = false; break;
         }
         else
            cout << "operator : " << next_character << endl;
      }
      else
      {
         arguments.putback(next_character);
         int value;
         arguments >> value;
         cout << "operand : " << value << endl;
      }
   }
   if(!valid)
     cout << "invalid postfix expression" << endl;

   return 0;
}

