postfix expression evaluation help

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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;
		}
		else if(str[i] = '-'){
			eval = x - y;
		}
		else if(str[i] = '*'){
			eval = x * y;
		}
		else if(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?
You are using the assignment operator = instead of the equality operator ==.
Here is a small example how to convert a string to a float
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <sstream>
#include <iostream>

int main()
{
	std::string str = "4.78";

	// create a input string stream
	std::istringstream iss(str); 
	
	// read float from stream
	float x;
	iss >> x;
	
	// print float value
	std::cout << x << std::endl;
}
oh well that was a stupid mistake by me, but either way im still having trouble with the conversions.
expStack is empty.
Topic archived. No new replies allowed.