简体   繁体   English

后缀表达评估

[英]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 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. 我以为我有一个字符串类型或char类型的堆栈,但是都没有用。 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 您应该使用top来获取top值,然后调用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);

链接可以帮助您解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM