C++堆栈;删除顶部值并放入变量中
C++ Stack; Remove top value and placing into variable
#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();
相关文章:
- 堆栈中大小变量输入错误 (C++)
- 变量周围的堆栈'...'已损坏
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- 运行时检查失败 #2 变量"A"周围的堆栈已损坏
- 如果我们通过引用传递变量,则递归中使用的堆栈空间量是否为零?
- 在 c++ 中确定堆栈上的变量范围
- 为什么在堆栈和堆上创建变量会产生相同的程序集代码?
- 为什么弹出我的堆栈会返回垃圾而不是初始变量?
- 堆栈粉碎 在我在代码中添加新变量以及一些操作后C++检测到
- 无法在具有常量变量大小的类中创建堆栈分配数组
- 运行时检查失败 #2 - 变量"e"周围的堆栈已损坏。发生
- 堆栈/帧指针作为外部变量
- "new"创建的实例的所有成员变量是否都存在于堆上而不是堆栈上?
- 变量周围的堆栈'sortArray'已损坏
- 堆栈变量超出范围时是否解除分配?
- 变量周围的堆栈'folderPath'已损坏
- 何时在函数中声明堆栈分配变量?
- 运行时检查失败 #2 - 变量周围的堆栈'...'已损坏
- C++ 大于堆栈的变量(堆栈溢出)
- 局部变量堆栈