I am trying to implement postfix-expression evaluation, here is my code:

#include<iostream>
#include<string.h>
using namespace std;
template < class T > class Stack {
private:
    T * s;
    int n;
public:
    Stack(int maxn) {
        s = new T[maxn];
        n = 0;
    }
    int empth() const {
        return n == 0;
    }
    void push(T item) {
        s[n++] = item;
    }
    int pop() {
        return s[--n];
    }
};

int main()
{
    string a = "598+46**7+*";
    int n = a.length();
    Stack < int >save(n);
    for (int i = 0; i < n; i++) {
        if (a[i] == "+")
            save.push(save.pop() + save.pop());
        if (a[i] == "*")
            save.push(save.pop() * save.pop());
        if ((a[i] >= '0') && (a[i] <= '9'))
            save.push(0);
        while ((a[i] >= '0') && (a[i] <= '9'))
            save.push(10 * save.pop() + (a[i++] - '0'));
    }

    cout << save.pop() << endl;

    return 0;
}

But I get a compile error (I am implementing it in linux (ubuntu 11.10)):

postfix.cpp:35:13: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
postfix.cpp:37:10: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]

How do I fix this?

有帮助吗?

解决方案

for(int  i=0;i<n;i++){
  if(a[i]=="+")
    save.push(save.pop()+save.pop());
  if(a[i]=="*")

You need to use single quotes when you are comparing characters

for(int  i=0;i<n;i++){
  if(a[i]=='+')
    save.push(save.pop()+save.pop());
  if(a[i]=='*')

其他提示

Here is link to evaluate postfix expression.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top