**How to evaluate a prefix expression with Stack -- Logic Errors**

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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
int exp(char* input)
{
    
    char*token=strtok(input, "");
    stack <int>num;
    stack <string> sym;
   
    int o1=0;
   
    int o2=0;
    int result=0;
    
    for(int i=strlen(input)-1; i>=0; i--)
	{
        
        if(isNumber(token)==true)
		{
            
            num.push((int)token);
         
        
		}

		else if(isOperator(token)==true&&sym.empty()==true)
		{
                    sym.push(token);
          

		}

		else if(isOperator(token)==true && !sym.empty() &&      precedence(token)>precedence(sym.top()))
		{

            sym.push(token);
             
            
		}

              while(!sym.empty()){

	            num.top()=o2;
                num.pop();
                num.top()=o1;
                num.pop();
                if(sym.top()=="+")
				{
                    result=o1+o2;
                    
                    
				}

                if(sym.top()=="-")
				{
                    result=o1-o2;
                   
                    
				}

                if(sym.top()=="*")
				{
                    result=o1*o2;
                    
                    
				}

                if(sym.top()=="/")
				{
                    result=o1/o2;
                    
                   
                    
                  
                    
				}

			  }
       

	}

                
   
     

     return(result);
        

	}

  
        
	


   


 


void main()


{
   char* input=new char[100];


  
   cout<<"Please enter an arithmetic expression"<<endl;

  cin>>input;

   int answer;

   answer=exp(input);

   cout<<"Answer to this expression"<<endl;

   cout<<answer<<endl;

    system("pause");


}




I've seen many posts on this topic, but none of them explain something that is troubling me. I am using two stacks here. How can I grab integers from my tokens? If a token is a number, how do I push it on to my integer stack?

The function in question here is int exp(char* input)

My goal is to take a prefix expression, and evaluate so I can get an answer.

For example:

(+12)=3

Last edited on
This translated pretty hideously into the codeblocks on here. If anyone needs any help reading anything in my code, just let me know. I appreciate all responses.
I don't know how to add/subtract/multiply/divide tokens of a string as ints. Can anyone help?
Could anyone take a quick look at this? I am completely lost. My understanding of stacks is pretty weak right now.
Topic archived. No new replies allowed.