c++ - 后缀表达式求值

标签 c++ stl stack

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

#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)

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

最佳答案

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

关于c++ - 后缀表达式求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3499927/

相关文章:

c++ - SQLINTEGER 的 ODBC 错误

c++ - switch 语句中的 strstr

c++ - 如何在 C++ 中获取多维 vector 的维度

c++ - Visual C++ 中与 reverse_iterator 相关的崩溃。是合法代码吗?

C, 变量 f1 周围的堆栈被破坏

c++ - 通过延迟的 self 转换来 boost MSM并行行为?

c++ - 如何合并两个包含 std::unique_ptr 的 vector ?

c - 堆栈问题: want to check if expression is correctly parenthesized and balancing and matching

c - Segmentation Fault Error Again——使用链表实现栈

C++ OOP 架构 : deciding between declaring an object from a base class or inheriting the base class