calculating an expression

Hello,
I need help to make it less messy but also make it work. It was suppose to evaluate an arithmetic expression without conversion to postfix.
Ps: I'm a beginner and I'll appreciate any comment or advice to get better.
Thanks in advance.

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
#include <stack>

using namespace std;


bool isOperand(char character);
bool isOperator(char character);
void Calculate(stack<char> operands, stack<char> operators, string expression);
void compute(stack<char> operands, stack<char> operators);

int main()
{
    stack<char> numbers ;
    stack<char> operators;
    string exp =  "1+2*3";
    Calculate(numbers,operators,exp);


  return 0;
}

bool isOperator(char character) {
    if (character == '+' || character == '-' || character == '*' || character == '/') {
       return true;
    }
    return false;
}
bool isOperand(char character) {
    if (!isOperator(character) && character != '(' && character != ')') {
        return true;
    }
    return false;
}

void Calculate(stack<char> operands, stack<char> operators, string expression)
{
  char c;
  char token;
  int result;
  for(int i = 0; i < expression.length(); i++)
{
  if (isOperand(c))
  token += c;
  if (c == ' ' || i == (expression.length() - 1)){
        if (isOperand(token)){
            operands.push(token);
            token = ' ';
        }
   }
   else if (isOperator(c))
   operators.push(c);
   if (operands.size() == 2){
       operands.top();
       operands.pop();
       operands.top();
       operands.pop();
       compute(operands,operators);
    }
 }
}

void compute (stack<char> operands,stack<char> operators){
    int num1;
    int num2;
    char op;
    switch(op)
    {
    case '+' :
        operands.push(num1 + num2);
        break;
    case '-' :
        operands.push(num1 - num2);
        break;
    case '*' :
        operands.push(num1 * num2);
        break;
    case '/' :
        operands.push(num1 / num2);
        break;
    }
}



1
2
3
4
5
 int num1;
    int num2;
    char op;

    

none of these in compute() have been initialised, so when you come to use them further down in that function they'll have nonsense values assigned to them.
Topic archived. No new replies allowed.