Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Postfix Expression Evaluation

$
0
0
My program needs to read in and evaluate a post fix expression read from an input file. I have to print out the expression read in followed by the results of evaluating said expression. I need to handle the addition, subtraction, and multiplication operators, as well as multi-digit numbers.

Now before I do all that, I wrote the program below to get an idea on how to do this. When I build it, the only warning I get is "comparison between signed and unsigned integer expression. So I run the program, enter an expression like "4(space)3(space)+(enter)" and then the program stops working. Can you look at the code and if there's something I'm missing?

#include <iostream>
#include <sstream>
#include <stack>
#include <limits>
#include <string>
#include <cctype>
#include <cstdlib>
using namespace std;

int main()
{
    string input;
    cout << "Enter a postfix expression: " << endl;
    getline(cin, input);


    std::stack<int>operation;
    stringstream temp;
    int number1;
    int number2;
    int output;
    int i = 0;
    while (i < input.length())
    {
        if (isdigit(input[i]))
        {
            operation.push(input[i]-'0');
        }
        else
        {
          number2 = operation.top();
          temp << operation.top();
          operation.pop();
          number1 = operation.top();
          temp << operation.top();
          operation.pop();
          switch(input[i])
          {
                  case '+': output = number1 + number2;
                  break;
                  case '-': output = number1 - number2;
                  break;
                  case '*': output = number1 * number2;
                  break;
                  case '/': output = number1 / number2;
                  break;
        }
        operation.push(output);
        }
        i++;
    }
    cout << "The result is: " << temp.str() << endl;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    return 0;
}


Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>