C ++堆栈;删除最高值并放入变量

时间:2016-05-06 23:51:06

标签: c++ stack

@echo off
setlocal enabledelayedexpansion

for /f "delims==" %%A in (trimlist.txt) do set string=%%A & echo !string:,=.!>>trimlist-new.txt

我的问题出在这两个TODO之下。我知道此时我需要做什么,但是我遇到麻烦,因为程序继续输出-1。

#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: 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();

1 个答案:

答案 0 :(得分:2)

如果要获取堆栈顶部的值,请使用stack::top(),而不是stack::pop(),然后再调用pop()以从堆栈中删除顶部元素。所以,你会这样做:

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