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

using namespace std;

void interpretExpressionFile(string filepath)
{

    // Declare a stack of ints
    stack<int>myStack;

    while (true)
    {
        char ch;
        fin >> ch;

        if (fin.eof())
        {
            break;
        }

        if (isspace(ch))
        {
            continue;
        }

        if (isdigit(ch))
        {
            int value = (ch - '0');

            // Push value onto the stack:
            myStack.push(value);
        }
        else
        {


我的问题在这两个TODO下。我知道这时我需要做的事情,但是由于程序继续输出-1我遇到了麻烦。

        // TODO: Remove top value from the stack placing it into value2
            myStack.pop();
            int value2 = -1;

            // TODO: Remove top value from the stack placing it into value2
            myStack.pop();
            int value1 = -1;

            int result;
            switch (ch)
            {
                case '+':  result = value1 + value2;  break;
                case '-':  result = value1 - value2;  break;
                case '*':  result = value1 * value2;  break;
                case '/':  result = value1 / value2;  break;
                default:  cout << "Unexpected operator: " << ch << endl;  return;
            }

            // TODO: Push the value in variable result back onto the stack:
            myStack.push(result);
        }
    }

    fin.close();


我的另一个问题就在这里。这也是我想弄乱的地方。

    // TODO: pop the top value off of the stack placing it into varresult:
    myStack.pop();
    int result = -1;
    cout << filepath << " - result is: " << result << endl;
}

int main()
{
    interpretExpressionFile("expression1.txt");
    interpretExpressionFile("expression2.txt");
    interpretExpressionFile("expression3.txt");
}

最佳答案

如果要在堆栈顶部获取值,请使用stack::top()而不是stack::pop(),然后再调用pop()从堆栈中删除顶部元素。因此,您可以:

int result2 = myStack.top();
myStack.pop();

10-07 19:30
查看更多