【问题标题】:Postfix-expression evaluation后缀表达式求值
【发布时间】:2011-03-30 19:40:36
【问题描述】:

我正在尝试编写一个评估后缀表达式的程序 代码:

#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;
}

但错误表明

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)

我以为我有一堆类型的字符串或类型的字符,但都不起作用。我该如何解决这个问题?

【问题讨论】:

  • 我强烈推荐 'char const* const a = argv[1]'

标签: c++ stl stack


【解决方案1】:

pop 函数只是弹出但不返回任何内容。

您应该使用top 获取最高值,然后调用pop

所以

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

应该改为:

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

【讨论】:

    【解决方案2】:

    link 可以帮助您解决问题。

    【讨论】:

      猜你喜欢
      • 2013-04-03
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 2011-12-05
      • 2017-05-02
      • 1970-01-01
      相关资源
      最近更新 更多