c++ postfix stack but invalid return

  c++, stack

I want to calculate postfix using I made the stack in c++

The results are good, but there is a problem.

I think division error

I want to make when division (second == 0) exception handling

at that time i want to output some text and quit the program

But the message(invalid return) appear.

How can i fix it?

here’s my stack and calcuate code

#include <string>
#include <iostream>
#include <cctype>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
#define MAX_STACK_SIZE 101

using std::cout; 
using std::cin;
using std::endl; 
using std::string;

class AStack{
    private:
        int top;
        double data[MAX_STACK_SIZE];
        double pop1;
    public:
        AStack(){top = -1;}
        ~AStack(){}

        int size(){ return top + 1;}

        void push(double e){
            data[++top]=e;
        }

        double pop(){
            if (top == -1)std::cout<<"empty"<<endl;
            else{
                pop1 = data[top];
                top--;
            }
            return pop1;
        }
};


double calc_postfix(char *expr[]){

    AStack stack; // stack
    double push_v; // push value
    double first,second; // evaluating value
    double value;
    char ch;

    for(int i=0;expr[i]!=NULL;i++){
        if (expr[i][0] >= '0' && expr[i][0] <= '9') 
        {
            value = atof(expr[i]); 
            stack.push(value); 
        }
        else{
            ch = expr[i][0];
            second = stack.pop(); 
            first = stack.pop();
            switch (ch)
            {
            case '+':
                stack.push(first+second);
                break;
            case '-': 
                stack.push(first-second);

                break;
            case '*':
                stack.push(first*second);

                break;
            case '/':
                if(second == 0){
                    std::cout<<"error";
                    exit(1);
                }      
                else stack.push(first/second);
                break;
            }
        }
    }
    return stack.pop();
}
int main()
{
    double result; 
    int k, len = 1;
    char scan[MAX_STACK_SIZE];    
    char *reversee[MAX_STACK_SIZE];

    fgets(scan,sizeof scan, stdin);

    reversee[0] = strtok(scan, " "); 
    k = 1;
    while (reversee[k] = strtok(NULL, " "))
    {
        k++;
        len++;
    }                   

    result = calc_postfix(reversee);
    printf("%.2f", result);

    return 0;
}

Source: Windows Questions C++

LEAVE A COMMENT