C++: Postfix to Infix Conversion - Homework Solution

  • Comp Sci
  • Thread starter DefaultName
  • Start date
In summary, this code is attempting to convert a postfix expression to a fully parenthesized infix expression using two stacks. The main function uses the MyStack class and prompts the user for a postfix expression. It then iterates through the expression and pushes operands to the s1 stack and operators to the temp stack. The prcd function is used to determine the precedence of operators and the postToIn function uses this to convert the postfix expression to infix, using minimal parentheses. The code has been tested with different postfix expressions and works correctly.
  • #1
DefaultName
180
0

Homework Statement



Convert a postfix expression to the corresponding fully parenthesized infix expression...

Homework Equations



None.

The Attempt at a Solution



Code:
#include<iostream>
#include<cctype>
#include<string>

#include "MyStack.h"
#include "MyStack.cpp"

using namespace std;

void displayGreeting();

int main()
{
	MyStack s1, temp;
	string postfix, infix, tempstr;
	char token;
	
	displayGreeting();

	cout << "Postfix expression: ";
	getline(cin, postfix);	
	cout << "You entered: " << postfix << endl;

	for (int i = 0; i < postfix.length(); i++)
	{
		token = postfix[i];
		if (!isspace(token))
		 if(isdigit(token) || isalpha(token))
			s1.push(token);			
		 else if(token == '+' || '-' || '*' || '/')
			temp.push(token);
	}
	
	s1.display(cout);
	temp.display(cout);	
	
	return 0;	
};

This is the code I have so far. I have two stacks

1) Stack s1, where it holds the digits or variables... such as a, b, 3...
2) Stack temp, where it holds the operands

I have a MyStack class, which is fine. I just need help developing an algorithm of converting something like this:

abc+* to (a*(b+c))... Any tips?
 
Physics news on Phys.org
  • #2
Code:
#include <stack>
#include <string>
using namespace std;

bool prcd(char op1, char op2) {
		if(op1 == '+' && op2 == '*')
			return false;
		else if(op1 == '*' && op2 == '+')
			return true;
		else if(op1 == '-' && op2 == '*')
			return false;
		else if(op1 == '*' && op2 == '-')
			return true;
		else if(op1 == '$' && op2 == '*')
			return true;
		else if(op1 == '*' && op2 == '$')
			return false;
		else if(op1 == '$' && op2 == '+')
			return true;
		else if(op1 == '$' && op2 == '-')
			return true;
		
		return false;

	}
std::string postToIn(std::string post) {
		
		std::string tmp = "";
		std::string infix = "";
		typedef struct Operand {
			std::string str;
			char oper;
		}Operand;
		typedef stack<Operand> OpndStk;
		OpndStk os;
		for(int i=0; i<post.size(); i++)
		{
			Operand o;
			if(isalpha(post[i]))
			{
				o.str = "";
				o.str += post[i];
				o.oper = ' ';
				os.push(o);
				continue;
			}
			else
			{
				Operand op2 = os.top();
				os.pop();
				Operand op1 = os.top();
				os.pop();
				if( op2.oper != ' ')
				{
					if(prcd(post[i],op2.oper))
					{
						op2.str.insert(0,"(");
						op2.str.append(")");
					}
				}
				if( op1.oper != ' ')
				{
					if(prcd(post[i],op1.oper))
					{
						op1.str.insert(0,"(");
						op1.str.append(")");
					}
				}
				tmp = op1.str+post[i]+op2.str;
				Operand t;
				t.str = tmp;
				t.oper = post[i];
				os.push(t);
				
			}
		}
		infix = os.top().str;
		os.pop();
		return infix;
	}

I have used extra info in each operand pushed on the stack to produce an infix which uses minimal parantheses(i.e uses only which are necessary). Idea is whenever u apply an operator, check whether any of its operands is itself result of applying any operator and, if yes, check whether the precedence of the most recent operator is higher than the operator applied to that operand and, if yes, u need parantheses around the operand. This is so because operators are applied in the order that they appear in postfix notation and while converting to infix, if an operator appearing earlier has lower precedence than the one appearing later then we need parantheses around the infix notation of the earlier operator.

I think the above para is very confusing... Sorry about that but i have been trying this for the last 12 hrs and my head is spinning too.
i tested this with the following postfix strings:
--> ABC*+
--> AB+C*
-->ABC-DEF*$*+

DefaultName said:

Homework Statement



Convert a postfix expression to the corresponding fully parenthesized infix expression...

Homework Equations



None.

The Attempt at a Solution



Code:
#include<iostream>
#include<cctype>
#include<string>

#include "MyStack.h"
#include "MyStack.cpp"

using namespace std;

void displayGreeting();

int main()
{
	MyStack s1, temp;
	string postfix, infix, tempstr;
	char token;
	
	displayGreeting();

	cout << "Postfix expression: ";
	getline(cin, postfix);	
	cout << "You entered: " << postfix << endl;

	for (int i = 0; i < postfix.length(); i++)
	{
		token = postfix[i];
		if (!isspace(token))
		 if(isdigit(token) || isalpha(token))
			s1.push(token);			
		 else if(token == '+' || '-' || '*' || '/')
			temp.push(token);
	}
	
	s1.display(cout);
	temp.display(cout);	
	
	return 0;	
};

This is the code I have so far. I have two stacks

1) Stack s1, where it holds the digits or variables... such as a, b, 3...
2) Stack temp, where it holds the operands

I have a MyStack class, which is fine. I just need help developing an algorithm of converting something like this:

abc+* to (a*(b+c))... Any tips?
 

1. How does postfix to infix conversion work in C++?

Postfix to infix conversion in C++ involves taking a mathematical expression in postfix notation, where operators are placed after their operands, and converting it to infix notation, where operators are placed between their operands. This is done by using a stack data structure and following a set of rules to rearrange the expression.

2. What is the purpose of converting postfix to infix in C++?

The purpose of converting postfix to infix in C++ is to make the expression easier to read and understand for both humans and computers. Infix notation is the standard mathematical notation, so converting to infix allows for easier evaluation of the expression and easier integration into other programs.

3. Can you provide an example of postfix to infix conversion in C++?

Sure, let's say we have the postfix expression "2 3 + 4 *". To convert this to infix, we would push each element onto a stack. When we encounter an operator, we pop the top two elements from the stack and place them on either side of the operator. So in this example, the first operation would be "3 + 2", resulting in "3 + 2 * 4". We continue this process until all elements have been processed, resulting in the infix expression "3 + 2 * 4".

4. Are there any limitations or restrictions when converting postfix to infix in C++?

Yes, there are a few limitations to keep in mind when converting postfix to infix in C++. One limitation is that the postfix expression must be well-formed, meaning it follows the proper syntax for postfix notation. Another limitation is that the expression can only contain operands and operators, and any other characters or symbols will result in an error.

5. Are there any other methods for converting postfix to infix in C++?

Yes, there are other methods for converting postfix to infix in C++. One method involves using a tree data structure to represent the expression and then traversing the tree to generate the infix notation. Another method involves using recursion to evaluate the postfix expression and generate the infix notation. However, the stack-based method is the most commonly used and efficient method for converting postfix to infix in C++.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
14
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Programming and Computer Science
Replies
4
Views
5K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
9
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
6K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
15
Views
2K
Back
Top