Postfix code

I am trying to execute a postfix code. for example, if a=6 and b=5, and you enter like ab+ it should result 11.

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
  #include <stack>
#include <iostream>
#include <string>
using namespace std;
double result(string);
int main()
{
	string astring;
	double res=result(astring);
	cout<<"Enter your postfix expression: "<<endl;
	cin>>astring;
	cout<<"The value is: "<<res<<endl;
	return 0;
}

double result(string bstring)
{
	stack<double> astack;
	double num1=0, num2=0, res=0;
	int len=bstring.length();
	for (int i=0;i<len;i++)
	{
	if ( (bstring[i]=='+') || (bstring[i]=='-') || (bstring[i]=='*') || (bstring[i]=='/') )
	{ num1=astack.top();
		astack.pop();
	num2=astack.top();
		astack.pop();
		if (bstring[i]=='+')
			res=num1+num2;
		else if (bstring[i]=='-')
			res=num1-num2;
		else if (bstring[i]=='*')
			res=num1*num2;
		else if (bstring[i]=='/')
			res=num1/num2;
		else 
			astack.push(res);
	}
	else
	{
		double temp=stod(bstring.substr(i,i+1));
		astack.push(temp);
	}
	}
	return astack.top();
}
Move line 9 after line 11. You're passing an empty string to the function, so bstring.lenght() == 0 and the loop is never executed.
'astack' is never filled. You probable want to put each character of the string in it.

----------
Next time please post details about your problem and any error you get.
Last edited on
@maeriden
I apologize and thanks because moving line 9 after 11 accommodates for a string value.
My real problem is how do I enter my string in such a way that it will compute it as a postfix.
No matter what way i enter a string it doesn't execute.
On line 37 you set the result of the operation that will then be returned on line 45. Except line 37 is executed only if bstring[i] is NOT an operation, but the if block containing it (line 23) is executed only if bstring[i] IS an operation.
You return the top of an empty stack, which causes undefined behavior.
i changed the return at 47 to return res;

When i enter 3 + 6 or 3 6 + the result is the same, which is zero.
shouldn't it be "3 6 +"
and the result should be 6?
I don't know why you get 0. When you enter the string, the >> operator reads the first word (should be "3") and puts it in 'astring'.
In the function the loop runs only one time (the length of "3" is 1), converts '3' to double and pushes it onto the stack. Then it is immediately returned.

Use getline() to read the whole string http://www.cplusplus.com/reference/string/string/getline/
Here's a reference to what you need to do http://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_algorithm
Topic archived. No new replies allowed.