hey there! ok i need help figuring out what is wrong with my code. i have to write a program that does addition and subtraction in stacking. but all im getting is error. some advice would be greatly appreciated thanks

here is the code

#include <iostream>
#include <stack>
#include <string>
#include <cmath>
using namespace std;

int main()
{       stack <int> s;
        int op1, op2;
        string str;
        int i;

        cout<<"enter a post fix expression: ";
        getline(cin, str);

        for(i=0;i<str.length();i++)
        {       if(isdigit(str[i]))
                {       s.push(str[i]);
                }else
                {       char ch = str[i];
                        switch(ch);
                        {       case '+': //addition
                                        op1=s.top();
                                        s.pop();
                                        op2=s.top();
                                        s.pop();
                                        s.push(op1+op2);
                                        break;
                                case '-': //substract
                                        op1=s.top();
                                        s.pop();
                                        op2=s.top();
                                        s.pop();
                                        s.push(op2-op1);
                                        break;
                                case 'q': //quits the calculator
                                         break;
                        }
                }
        }
                if(!empty())
                {       cout<<"the answer is: s.top()"<<endl;
                }else
                {       cout<<"error";
                }

return 0;
}

Edited 3 Years Ago by Nick Evan: Fixed formatting

throw in some output statements within your code to see what top is after each push to be sure you are actually putting something in the stack. I'm concerned that you declare the stack using type int but you are trying to push type char onto the stack. That also means you are trying to do math with type char. This might work, as char are ints per a character set someplace in the background, but I'm not sure it will. This is how I'd find out. If you like using a debugger to follow variable values through a program instead of sprinkling output statements in, by all means do so.

ok i took ur advice an put some output statements an changed the <int> to <char> but the error message is the same this is what it says....


calculator.cpp: In function âint main()â:
calculator.cpp:22: error: case label â'+'â not within a switch statement
calculator.cpp:30: error: case label â'-'â not within a switch statement
calculator.cpp:38: error: case label â'q'â not within a switch statement
calculator.cpp:43: error: âemptyâ was not declared in this scope

This article has been dead for over six months. Start a new discussion instead.