Xdroid
Xdroid

Reputation: 5

Evaluate expression with stack

Hi I'm trying to write a program in c++ that evaluates expression using a stack but the result is a random number(an address memory maybe but it's not a pointer). Here's the Stack template`

#ifndef STACK_H_
#define STACK_H_
template <class Item>
class Stack {
public:
    static const size_t Capacity=100;
    Stack(){used=0;};
    void push(const Item& insert){data[used]=insert; used++;};
    void pop(){used--;};
    Item top(){return data[used-1];};
private:
    Item data[Capacity];
    size_t used;
};

#endif /* STACK_H_ */
`

and this is the main with the 2 functions used

#include <iostream>
#include <cstring>
#include "Stack.h"
using namespace std;

double manage_stack(istream& insert);
void evaluate(Stack<double> numbers, Stack<char> operations);

int main(){
    double result;
    result=manage_stack(cin);
    cout<<result;
    return 0;
}

double manage_stack(istream& insert){
    double number;
    char symbol;
    Stack<double> numbers;
    Stack<char> symbols;
    while(insert.peek()!='\n'){
    if(isdigit(insert.peek())||insert.peek()=='.'){
        insert>>number;
        numbers.push(number);
    }
    else if(strchr("+-*/",insert.peek())!=NULL){
        insert>>symbol;
        symbols.push(symbol);
    }
    else if(insert.peek()==')')
        evaluate(numbers, symbols);
    else
        insert.ignore();
    }
    return numbers.top();
}

void evaluate(Stack<double> numbers, Stack<char> operations){
    double n1, n2;
    n2=numbers.top();
    numbers.pop();
    n1=numbers.top();
    numbers.pop();
    switch(operations.top()){
    case'+':numbers.push(n1+n2);
            break;
    case'-':numbers.push(n1-n2);
            break;
    case'*':numbers.push(n1*n2);
            break;
    case'/':numbers.push(n1/n2);
            break;
    }
    operations.pop();
}

Can anyone help me? Thanks in advance!

Upvotes: 0

Views: 422

Answers (1)

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29022

Item data[]; is a non-standard extension and is being used improperly. See this answer to see how it's supposed to be used. You haven't allocated any memory for it, as such you are in undefined behavior. Your program can have any behavior, including running and returning random values. For your application, you should consider using std::stack instead of your Stack class. It looks like you can substitute it directly.

#include <stack>
template<class T>
using Stack = std::stack<T>;

I've tried to run your example and the result is still incorrect, but it doesn't return random values. It always returns the first operand twice.

I've answered why the result appears random. If you want to know why your parser still doesn't give the correct result, I suggest using a debugger. There is a quite a bit of work left to do. For example, there doesn't seem to be any iteration over the input. You will need some sort of loop or recursion.

Upvotes: 3

Related Questions