I need help on my reverse polish notation calculator

Hi_mynameis picture Hi_mynameis · Dec 11, 2014 · Viewed 7.9k times · Source

I am working on a program to make a reverse polish notation calculator and I am wondering if anyone can give me some hints. The calculator will intake a single line from the user like 2 3 + 7 4 - *; with spaces in between and I am suppose to print one result after every operation.

here is part of my code

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

int main() {
  stack<float>stack;
  int i;
  float num,result,first,second;
  char op,ch;
  string str;

  getline(cin,str);
  istringstream is(str);
  for(int i=0;i<str.size();i++) {
    is>>num;
    stack.push(num);
  }
  for (i=0;i<str.size();++i) {
    ch=str[i];
  }
  if (ch=='+'||'-'||'*'||'/') {
    if (ch='+') {
      first=stack.top();
      stack.pop();
      second=stack.top();
      stack.pop();
      result=first+second;
      stack.push(result);
      cout<<result;
    }
//  } // missing from question
//}

I have been getting weird numbers as the outcome. Am I reading in my stack correctly?

Answer

OmnipotentEntity picture OmnipotentEntity · Dec 11, 2014

This is probably not your only issue, but you have:

if (ch=='+'||'-'||'*'||'/') {

when you probably actually mean:

if (ch=='+' ||
    ch=='-' ||
    ch=='*' ||
    ch=='/') {

Also right under that you have:

if (ch='+') {

you probably actually mean:

if (ch=='+') {

= is assignment (you are setting ch to '+') whereas == is comparison (you are testing whether or not ch is equal to '+')