RPN 计算器(将操作数应用于堆栈的问题)

RPN Calculator (issues with applying operands to the stack)

我目前正在为 class 构建 RPN 计算器,它必须通过一堆整数和各种函数来运行。它还必须通过 cin 语句获取输入,然后将其分类为整数或操作数,然后将其压入堆栈或从 class 启动适当的函数进行计算。

其中大部分我已经弄清楚并正在工作,但是我遇到了一个我无法弄清楚的非常奇怪的问题。

我的第一组数字和第一个操作数很好(例如,我输入 1 2 3 并且堆栈将显示 3、2、1 作为内容)但是在我应用第二个操作数之后我'我在每个答案前都填入了零。

示例:

输入:1 2 + 2 *

预期输出:6

我得到的是:0、2、0、3

我不确定这是否是我的堆栈 push() 函数、main 函数或其他地方的错误。我没能找到它。任何帮助将不胜感激,即使只是方向正确的一点!

这是我假设在某处导致问题的部分代码:

主要功能:

int main(){

  Stack mystack;

  std::string getIt; // taken as input
  int pushIt;  // converted to int and pushed if nessecary

  do{
    // get user input
    std::cin >> getIt;
    if(getIt == "@"){};
    if(getIt == "!") mystack.negate();
    if(getIt == "+") mystack.add();
    if(getIt == "-") mystack.subt();
    if(getIt == "/") mystack.div();
    if(getIt == "%") mystack.mod();
    if(getIt == "SUM") mystack.sumof();
    if(getIt == "R") mystack.reverse();
    if(getIt == "#") mystack.print();
    if(getIt == "$") mystack.clear();
    else {
      pushIt = atoi(getIt.c_str()); // I have no idea if this was
                                    //utilized correctly, feel free
     mystack.push(pushIt);          // to correct me here if not..
    }
   }
  while(getIt!="@"); // breaks on @
  return 0;
 }

推送、弹出和顶部运算符:

void Stack::push(const int& val){
  Node* newNode = new Node;
  newNode->data = val;
  if(!head){
    head = newNode;
    return;
  }
  newNode->next = head;
  head = newNode;
}


void Stack::pop(){
  if(!head)
    return;
  if(head->next == NULL){
    delete head;
    head = NULL;
    return;
  }
  Node* deleteIt = head;
  head = head->next;
  delete deleteIt;
  return;
}


const int& Stack::top() const throw(Oops) { //Oops returns
  if(head == NULL){                     // an error variable
    std::cout<<"ERROR!! : No values in the stack.";
  }      
  return head->data;
}
// I also don't know if I used the throw right here.. 

而且,以防万一我实际上在这里做错了......这是我的一个操作函数(+),其他的都以类似的方式编码。

void Stack::add(){
  int num1 = top();
  pop();
  int num2 = top();
  pop();
  int sum = num2+num1;
  push(sum);
  return;
}

谢谢!

你的流量控制不正确。考虑当用户输入 +:

时会发生什么
if(getIt == "+") mystack.add();   // <== this happens
if(getIt == "-") mystack.subt();  // nope
if(getIt == "/") mystack.div();   // nope
// ... snip ... 
if(getIt == "$") mystack.clear(); // nope
else {                            // this else is associated ONLY with the 
                                  // previous if. As a result...
  pushIt = atoi(getIt.c_str());   // <== this happens too!
  mystack.push(pushIt);
}

您将 + 处理为加法操作数 数字 - 和 atoi("+") == 0。问题是你所有的 if 都是独立的,它们不应该是:

if (getIt == "+") ...
else if (getIt == "-") ...
else if (getIt == "/") ...
...
else {
    // handle int here
}