开发者

Postfix-expression evaluation

I am trying to write a program for evaluating postfix-expression code:

#include <iostream>
#include <cstring>
#include <stack>
#include <ostream>
using namespace std;
int main(int argc,char *argv[]){
    char *a=argv[1];
    int开发者_JAVA百科 n=strlen(a);
    stack<int>s;
    for (int i=0;i<n;i++)
    {
        if (a[i]=='+')
            s.push(s.pop()+s.pop());
        if (a[i]=='*')
            s.push(s.pop() * s.pop());
        if ((a[i]>='0') && (a[i]<='9'))
            s.push(0);
        while ((a[i]>='0') && (a[i]<='9'))
            s.push(10*s.pop()+(a[i++]-'0'));
    }
    cout<<s.pop()<<endl;
    return 0;
}

But errors says that

1>c:\users\david\documents\visual studio 2010\projects\compilers\compilers.cpp(16): error C2296: '*' : illegal, left operand has type 'void'
1>c:\users\david\documents\visual studio 2010\projects\compilers\compilers.cpp(16): error C2297: '*' : illegal, right operand has type 'void'
1>c:\users\david\documents\visual studio 2010\projects\compilers\compilers.cpp(21): error C2297: '*' : illegal, right operand has type 'void'
1>c:\users\david\documents\visual studio 2010\projects\compilers\compilers.cpp(25): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'void' (or there is no acceptable conversion)

I thought that I have a stack of type string or type char, but neither works. How do I fix this problem?


The pop function justs pops but does not return anything.

You should use the top to get the top value and then call pop

So

s.push(s.pop() * s.pop());

should be changed to:

int temp1 = s.top();
s.pop();
int temp2 = s.top();
s.pop();
s.push(temp1 * temp2);


This link may help you to solve your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜