I have a program where i need to enter a postfix expression, and then it will evaluate it. All of the code was provided for the most part, but im having trouble with the evaluation part.
float postfixExpression(string str) {
float eval = 0.0;
vector<string> tokens;
stack<float> expStack;
float x = 0.0, y = 0.0;
// process to get a vector of tokens
tokens = tokenize(str, " ");
// Now do your postfix expression evaluation here.
for(int i = 0; i < tokens.size(); i++){
str = tokens[i];
if(!isdigit(str[i])){
x = expStack.top();
expStack.pop();
y = expStack.top();
expStack.pop();
}
if(str[i] = '+'){
eval = x + y;
}
elseif(str[i] = '-'){
eval = x - y;
}
elseif(str[i] = '*'){
eval = x * y;
}
elseif(str[i] = '/'){
eval = x / y;
}else{
expStack.push(str[i]);
}
}
return eval;
}
I know what i need to do is Convert the string into a constant string using c_str(), and then convert that into a float using atof before i push it onto the stack. Ive tried x = atof( str.c_str() ); and many different variations of that right before expStack.push(str[i]); but nothing seems to work. Any suggestions?