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

时间:2015-04-20 02:25:13

标签: c++ stack rpn

我正在开发RPN计算器,用于必须通过一堆int和各种函数运行的类。它还必须通过cin语句获取输入,然后将其分类为整数或操作数,并将其推入堆栈或从类中启动适当的函数进行计算。

我发现并工作的大部分内容,但是我有一个非常奇怪的问题,我无法弄明白。

我的第一组数字和第一个操作数很好(例如,我输入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;
 }

Push,Pop和Top Operators:

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;
}

谢谢!

1 个答案:

答案 0 :(得分:2)

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

时会发生什么
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
}