Hi,
I'm supposed to write a program for school that performs postfix evaluation.
It's going pretty good except I've run into a small problem. When I try to print my final value, numStack.top(), I'm just getting garbage. I know this is because it's empty, and it's empty because of line 38 in my second IF statement. I can't seem to come up with a way around this issue.
Any sort of help would be appreciated.
As it is, your program only interprets single digit integers, and does not accept any separator (whiespace).You might want to reconsider this.
Moreover, I don't see the use of that while loop.
ps: on the style, most people prefer a switch (...) case... statement rather thant so many ifs
btw, you know that "6+5" is not postfix, right ? So raising an exception should not be a surprise
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <string>
#include <stack>
#include <stdio.h>
#include <math.h>
usingnamespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string expression = "6+5";
int i, intValue, answer;
float x, y;
int num1 , num2 ;
bool endOfFile = false, canCalc = false;
stack<int> numStack;
//while end of file isn't reached...
while(endOfFile == false)
{
for(i = 0; i <= expression.length() - 1; i++)
{
//if the current character is a digit, convert it to an int and push in into the stack
if(isdigit(expression[i]))
{
stringstream ss(expression[i]);
ss >> intValue;
numStack.push(intValue);
}
}
}
while(endOfFile == false)
{
for(i = 0; i <= expression.length() - 1; i++)
{
//if the current character is a digit, convert it to an int and push in into the stack
if(!isdigit(expression[i]) &&(numStack.top() >= 0 )
{
x = numStack.top();
numStack.pop();
y = numStack.top() ;
numStack.pop();
if(expression[i] == '+')
{answer = y + x;}
if(expression[i] == '-')
{answer = y - x;}
if(expression[i] == '/')
{answer = y / x;}
if(expression[i] == '*')
{answer = y * x;}
if(expression[i] == '^')
{answer = pow(y, x);}
numStack.push(answer);
}
}
}
//exit loop if end of file is reached
if(i == expression.size())
{
endOfFile = true;
}
}
//print solution
if( numStack.top() > 0 )
cout << numStack.top() << endl;
system("PAUSE");
return 0;
}
@johnbob I know about everything it doesn't do. I'm still in the first steps of this program and I haven't taken time to worry about all the details yet. I'm only asking about what I stated specifically.