Result for infix to postfix converter

Hello friends. I'm new here and would like help in this code that converts infix expression to postfix. The code is converting correctly, but I would like to get the result of the operation. Can anyone help me with a hint on converting the "stringstream output" Or the "output.str ()" in an "int result", with the result of the operation?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <sstream>
#include <stack>
#include <limits>
#include <string>
using namespace std;

int priority(char a) {
    int temp;
    if (a == '^')
        temp = 1;
    else  if (a == '*' || a == '/')
        temp = 2;
    else  if (a == '+' || a == '-')
        temp = 3;
    return temp;
}
int main() {
    string infix;
    getline(cin, infix);

    stack<char> operator_stack;

    stringstream output;

    for (unsigned i = 0; i < infix.length(); i++) {
        if (infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/' || infix[i] == '^') {
            while (!operator_stack.empty() && priority(operator_stack.top()) <= priority(infix[i])) {
                output << operator_stack.top();
                operator_stack.pop();
            }
            operator_stack.push(infix[i]);
        } else if (infix[i] == '(') {
            operator_stack.push(infix[i]);
        } else if (infix[i] == ')') {
            while (operator_stack.top() != '(') {
                output << operator_stack.top();
                operator_stack.pop();
            }
            operator_stack.pop();
        } else {
            output << infix[i];
        }
    }

    while (!operator_stack.empty()) {
        output << operator_stack.top();
        operator_stack.pop();
    }

    cout << output.str() << endl;
    

    return 0;
}
Hello arielselbach,

the first thing you need is a separator in your output stream. A whitespace would suffice. Add it whenever a non numeric value appears. It actually doesn't matter if you have more than one whitespace.

The second thing is that you need a second stack for the numbers. Place each number on the stack until an operator is reached then pop the last number and apply the operation to the top number.
The operator can be determined when the stream raises an error on reading a numeric value. When this error arise you need to use ignore. See:

http://en.cppreference.com/w/cpp/io/basic_istream/ignore

for how to handle that.
Topic archived. No new replies allowed.