Reputation: 83
#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
{
My problem is here beneath these two TODOs. I know what I need to do at this point, but I am having trouble as the program continues to output -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();
My other problem lies here. This is where I think I am getting messed up as well.
// 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");
}
Upvotes: 1
Views: 1391
Reputation: 747
If you want get the value at the top of the stack, then use stack::top()
, not stack::pop()
and then call pop()
afterwards to remove the top element from the stack. So, you'd do:
int result2 = myStack.top();
myStack.pop();
Upvotes: 4