c++ - 后修复计算器,返回错误值

标签 c++ stack postfix-notation

我正在编写一个程序来实现后缀计算器,它给了我完全错误的答案。 非常感谢帮助

class stacks {
public:
  typedef int List;
  static const int size = 100;

  stacks() {
    use = 0;
  }

  void push(List entry) {
    data[use] = entry;
    ++use;
  }
  List pop() {
    if(!empty()) {
      --use;
      return data[use];
    }
  }

  bool empty() const {
    return use == 0;
  }
  int Size() const {
    return use;
  }

private:
  List data[size];
  int use;

};

int main() {

  stacks s;
  string input;

  int final;

  ifstream infile("foo.txt",ios::in);

  while (getline(infile, input))
    cout << "Expression: ";
  for (int i = 0; i<input.length(); i++) {

    cout << input[i];
    auto oper1 = s.pop();
    auto oper2 = s.pop();

    if(input[i] == '1' || input[i] == '2' || input[i] == '3' || input[i] == '4' ||     nput[i] == '5' || input[i] == '6' || input[i] == '7' || input[i] == '8' || input[i] == '9')
      s.push(input[i] - '0');

    if(input[i] == '+')
      s.push(oper1 + oper2);
    if(input[i] == '-')
      s.push(oper1 - oper2);
    if(input[i] == '*')
      s.push(oper1 * oper2);
    if(input[i] == '/')
      s.push(oper1 / oper2);

  }
  final = s.pop();
  cout << endl << "Value = " << final << "." << endl << endl;

}

您有什么建议? 谢谢

最佳答案

您需要等待 pop() 直到您知道您有一个运算符。你在不应该的时候从堆栈中弹出东西。

关于c++ - 后修复计算器,返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22901742/

相关文章:

Java 通用可序列化、可迭代堆栈

c++ - 使用堆栈检查正确的HTML标记的C++程序

代码厨师 : reverse Polish Notation

java - 使用堆栈理解 Java 代码中的后缀表达式求值

c++ - 对于多态类的对象,对象的地址和指向对象的指针是否相同?

c++ - 在 Visual Studio 中调用 std::swap 时的 std::bad_function_call

c - 缓冲区溢出(返回地址)

javascript - 使用 javaScript 将前缀表达式转换为中缀表达式

C++11 的采用和兼容性策略?

c++ - C++ vector 拥有对象的所有权