C++堆栈;删除顶部值并放入变量中

C++ Stack; Remove top value and placing into variable

本文关键字:变量 堆栈 删除 顶部 C++      更新时间:2023-10-16
#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();