2

我正在尝试用 C++ 实现一个 RPN 计算器。以下是该程序的基本部分。

#include <iostream>
#include <stack>
#include <cctype>
#include <string>

using namespace std;

bool isNumberString(string &str);

int main()
{
    cout << "RPN Calculator Simulation" << endl;

    while (true)
    {
        string input;
        stack<double> operandStack;
        double lhs, rhs, result;

        cout << "> ";
        getline(cin, input);

        if (input == "Q" || input == "") {
            return 0;

        } else if (isNumberString(input)) {
            operandStack.push(atof(input.c_str()));

        } else if (input == "+") {
            rhs = operandStack.top();
            lhs = operandStack.top();

            result = lhs + rhs;
            operandStack.push(result);

        } else {
            cout << "Invalid command. Please try again." << endl;
        }
    }

    return 0;
}

bool isNumberString(string &str)
{
    if (str.length() == 0) return false;

    int numberOfDots = 0;

    for (size_t i = 0; i < str.length(); i++)
    {
        if (str[i] == '.')
        {
            if (++numberOfDots > 1) return false;
        }
        else if (!isdigit(str[i]))
        {
            return false;
        }
    }

    return true;
}

运行并输入两个数字并在命令行提示符中输入“+”时,我收到“表达式:deque iterator not dereferencable”的错误。

任何人都可以就我的代码问题提供建议吗?

提前致谢。

4

1 回答 1

1

您一定遇到了运行时错误

当您每次在循环中创建新堆栈时,输入时while什么都没有stack+

stack<double> operandStack;

应该在外while循环

结果也是根据错误的输入计算的,您需要修复那些修改逻辑的部分。

于 2013-09-15T08:37:05.183 回答