2010-08-17 150 views
1

我想写评价后缀表达 代码的程序:后缀表达式评估

#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,但都不起作用。我该如何解决这个问题?

+0

我强烈建议'char const * const a = argv [1]' – Chubsdad 2010-08-17 06:57:42

回答

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); 
0

link可以帮助你解决你的问题。