stringstream repeating last item.....why?!

Oct 12, 2013 at 9:31pm
My code is below, the only problem I am coming across it that instead of the stringstream stopping after the last token has been evaluated, it is repeating the last token in the list, thus screwing up the output. It is like this in another method that I wrote, so my logic concerning the stringstream and using it is flawed. Any ideas? What don't I get here? If not clear by the method name, this is to evaluate a postfix expression. Thanks in advance for any help you can give!!
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
string ExpressionManager::postfixEvaluate(string postfixExpression){
	stack<int> st;
	stringstream ss;
	ss << postfixExpression;
	string Current;
	ss >> Current;
	int Holder;
	string Ops = "+-*/%";

	while(Current != ""){

		if(Ops.find(Current) != std::string::npos){
			cout<<" 1 "<<"CURRENT ="<<Current;

			int R;
			int L;
			if(!st.empty()){
				cout<<" 1.1 ";
				R = st.top();
				cout<<"R="<<R;
				st.pop();
				if(!st.empty()){
					cout<<" 1.1.1 ";
					L = st.top();
					cout<<"L="<<L;
					st.pop();
				}//end if
				else{
					cout<<" 1.1.2 ";
					return "invalid";
				}//end else
			}//end if
			else{
				cout<<" 1.2 ";
				return "invalid";
			}
			if(Current == "+"){
				cout<<" 1.3 ";
				 st.push(L+R);
			}
			else if(Current == "-"){
				cout<<" 1.4 ";
				st.push(L-R);
			}
			else if(Current == "*"){
				cout<<" 1.5 ";
				st.push(L*R);
			}
			else if(Current == "/"){
				cout<<" 1.6 ";
				st.push(L/R);
			}
			else if(Current == "%"){
				cout<<" 1.7 ";
				st.push(L%R);
			}

			ss >> Current;
		}//end if
		else{
			cout<<" 2 ";
			Holder = atoi(Current.c_str());
			st.push(Holder);
			ss >> Current;
		}//end else
	}//end while
	if(st.empty()){
		cout<<" 3 ";
		return "invalid";
	}
	else{
		cout<<" 3.1 ";
		stringstream ss;
		ss << st.top();
		string str = ss.str();
		return str;
	}

}
Oct 12, 2013 at 9:42pm
Could you give a typical example of the input postfixExpression which this function is to process please.
Oct 12, 2013 at 9:45pm
1 5 - 2 / 89 -

is one of them.
Oct 12, 2013 at 10:37pm
Thanks. That helped.

You could simply change line 10 from:
 
    while (Current != "")

to:
 
    while (ss)


However, the code would be simpler if you were to replace that line with:
 
    while (ss >> Current)

and then remove this ss >> Current; from all of the lines 6, 58 and 64.
Last edited on Oct 12, 2013 at 10:38pm
Oct 12, 2013 at 11:07pm
Thank you!!! That fixed....well that problem is fixed at least haha. Thanks for your help!
Topic archived. No new replies allowed.