Question

In: Computer Science

Write a program that takes an infix expression as input and produces a postfix expression. The...

Write a program that takes an infix expression as input and produces a postfix expression. The infix and postfix expressions are in the form of vectors of strings. We will test with a main method that takes a file name as input from the command line. We will test your implementation using printPostFix() method.   There are sample input and output files in this folder. You may edit the header file.

Example 1

infix expression = apple + banana * cat

vector inFixTokens = {"apple", "+", "banana", "*", "cat"}

postfix expression = apple banana cat * +

vector postFixTokens = {"apple", "banana", "cat", "*", "+"}

Example 2

infix expression = (apple + banana) * cat ^ dog + egg

vector inFixTokens = {"(", "apple", "+", "banana", ")" , "*", "cat", "^", "dog", "+", "egg"}

postfix expression = apple banana + cat dog ^ * egg +

vector postFixTokens = {"apple", "banana", "+", "cat", "dog", "^", "*", "egg", "+"}

Use the algorithm given in the lecture slides on stacks.

Use the following header file to create a PostFixTokens class.

PostFixTokens.h

We will test your implementation by creating instances of PostFixTokens and calling createPostFix and printPostFix. *Do not change the method signatures because we will use them to test your implementation.*

Operators: ^, *, /, +, -

Precedence: ^ > * / > + -

You must account for parentheses ), (

Only binary operators. No unary operators. Minus sign (-) is not used for negation, only as a binary operator.

If the tokens of inFixTokens are an invalid expression, then any call to getPostFixTokens, printPostFix, or createPostFix should throw a std::invalid_argument exception.

Header Given:

#ifndef PostFixTokens_h
#define PostFixTokens_h
#include 
#include 
#include 

using namespace std;

class PostFixTokens {
public:
PostFixTokens();
PostFixTokens(vector inFix);
~PostFixTokens();

    vector getPostFixTokens();
    vector getInFixTokens();
    void setInFixTokens(vector inFix);
    void printPostFix();
    void printInFix();
    void createPostFix();


private:
vector inFixTokens;
vector postFixTokens;
    
};


#endif /* PostFixTokens_h */

Tester File given:

#include
#include
#include
#include
#include "PostFixTokens.h"

class ostream_suppressor {
std::ostream &out;
std::ostringstream buffer;
std::streambuf *old_buffer;
public:
ostream_suppressor(std::ostream &out) : out(out) {
old_buffer = out.rdbuf(buffer.rdbuf());
}

~ostream_suppressor() {
out.rdbuf(old_buffer);
}
};

static const std::list token_types = {
std::regex("^(-?\\d+)"), // numbers
std::regex("^[\\(\\)\\+\\-\\*\\/%\\^]"), // operators
std::regex("^[[:alpha:]]([[:alnum:]_-]*)") // variables
};

std::vector tokenize(const std::string infixExp) {
auto tokens = std::vector{};
auto matches = std::smatch{};

auto it = begin(infixExp), endIt = end(infixExp);
while(it != endIt) {
for(const auto &token_type: token_types) {
if(std::regex_search(it, endIt, matches, token_type)) {
tokens.push_back(matches[0]);
// move the iterator forward to the end of the found token
it += matches[0].length()-1;
break;
}
}
++it;
}

return tokens;
}

void printTokens(std::vector &tokens) {
if(tokens.size() == 0) return;

std::cout << tokens[0];
std::for_each(begin(tokens)+1, end(tokens), [](const auto &token) {
std::cout << " " << token;
});
std::cout << std::endl;
}

int main() {
std::string infixExp;

while(std::getline(std::cin, infixExp)) {
try {
auto inFixTokens = tokenize(infixExp);

std::vector postFixTokens;
{
ostream_suppressor supressor(std::cout);
PostFixTokens tokens(inFixTokens);
tokens.createPostFix();
postFixTokens = tokens.getPostFixTokens();
}

printTokens(postFixTokens);
} catch (std::invalid_argument &e) {
std::cout << "Invalid infix expression\n";
} catch (std::exception &e) {
std::cout << "Unexpected exception thrown with message " << e.what() << "\n";
}
}
}

Solutions

Expert Solution

The c++ code for the PostFixTokens.h Headerfile is shown below:

#ifndef PostFixTokens_h
#define PostFixTokens_h
#include<bits/stdc++.h>
using namespace std;
class PostFixTokens {
public:
PostFixTokens();
PostFixTokens(vector<string> inFix);
~PostFixTokens();

vector<string> getPostFixTokens();
vector<string> getInFixTokens();
void setInFixTokens(vector<string> inFix);
void printPostFix();
void printInFix();
void createPostFix();


private:
vector<string> inFixTokens;
vector<string> postFixTokens;
  
};
bool isOperator(string s){
   if(s=="+" || s=="*" || s=="^" || s=="/" || s=="-")
       return true;
   else
       return false;
}
int precition(string s){
   if(s=="^"){
       return 3;
   }
   else if(s=="*" || s=="/"){
       return 2;
   }
   else if(s=="+"|| s=="-"){
       return 1;
   }
}
void PostFixTokens::createPostFix(){
   stack<string> Stack;
   Stack.push("$");
   for(string s:inFixTokens){
       if(isOperator(s)==false){
           postFixTokens.push_back(s);
       }
       else if(s=="("){
           Stack.push("(");
       }
       else if(s==")"){
           while(Stack.top()!="$" && Stack.top()!="("){
               postFixTokens.push_back(Stack.top());
               Stack.pop();
           }
           if(Stack.top()=="("){
               Stack.pop();
           }
       }
       else{
           while(Stack.top()!="$" && precition(s)<=precition(Stack.top())){
               postFixTokens.push_back(Stack.top());
               Stack.pop();
           }
           Stack.push(s);
       }

   }
   while(Stack.top()!="$"){
       postFixTokens.push_back(Stack.top());
       Stack.pop();
   }
}
void PostFixTokens::printPostFix(){
   for(string s:postFixTokens){
       cout<<s<<" ";
   }
   cout<<endl;
}
void PostFixTokens::printInFix(){
   for(string s:inFixTokens){
       cout<<s<<" ";
   }
   cout<<endl;
}
void PostFixTokens::setInFixTokens(vector<string> inFix){
   for(string s:inFix){
       inFixTokens.push_back(s);
   }
}
vector<string> PostFixTokens::getPostFixTokens(){
   return postFixTokens;
}
vector<string> PostFixTokens::getInFixTokens(){
   return inFixTokens;
}

#endif


Related Solutions

**write a java program infix to postfix**showing the expression tree*** I. Input All input data are...
**write a java program infix to postfix**showing the expression tree*** I. Input All input data are from a file "in.dat". The file contains a sequence of infix form expressions, one per line. The character '$' is an end mark. For example, the following file has four infix form expressions: 1 + 2 * 3 ^ ! ( 4 == 5 ) $ 3 * ( 6 - 4 * 5 + 1) + 2 ^ 2 ^ 3 $ 77...
Using java.util.Stack and java.util.StringTokenizer to write a program that converts an infix expression to a postfix...
Using java.util.Stack and java.util.StringTokenizer to write a program that converts an infix expression to a postfix expression using data from infix.dat. Make sure your program can handle negative number. If the input expression can’t be converted, display error message.(1.5 points) (Should remove parentheses) infix.dat 5 * 6 + -10 3 - 2 + 4 7 ( 3 * 4 - (2 + 5)) * 4 / 2 10 + 6 * 11 -(3 * 2 + 14) / 2 2...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix expression. For example, 1 + 2 * 3 becomes 2 3 * 1 +. Also, evaluate the expression to ensure the expression is correct.
java Convert the following Infix expression to a Postfix expression. Show all work                            Infix Expres
java Convert the following Infix expression to a Postfix expression. Show all work                            Infix Expression                                                 Stack                             Postfix Expression ---------------------------------------------------------------------------------------------------------------------------- 8 - 9*(2 + 1/4) + 3*7                                                     (empty)                            (blank) Evaluate the following Postfix expression. Once again, show all work.            Postfix                                               Stack                     Result           ---------------------------------------    --------------------    --------------            2 7 + 12 4 / * 8 5 + -
Write a class PostFix that has one method covert that converts an infix expression (as a...
Write a class PostFix that has one method covert that converts an infix expression (as a string input) to a postfix. Then Test it in a different class. code in java.
Implement an infix expression to postfix expression convertor in C++. Note: - Support +, -, *,...
Implement an infix expression to postfix expression convertor in C++. Note: - Support +, -, *, /, ( and ) in infix expressions. - Operands will be nonnegative only. - Assume infix expressions are valid and well formatted (one blank space to separate operand/operator) For example, - 3 * 4 + 5 ➔ 3 4 * 5 + - 3 + 4 * 5 ➔ 3 4 5 * + - (3 + 4) * (5 + 6) ➔ 3...
Convert an infix expression to its postfix representation in JAVA
Convert an infix expression to its postfix representation in JAVA
(Convert infix to postfix) Note: Postfix notation is a way of writing expression without using parentheses....
(Convert infix to postfix) Note: Postfix notation is a way of writing expression without using parentheses. For example, the expression ( 11 + 12 ) * 13 would be written as 11 12 + 13 * Assume that ALWAYS there is a space between operands and operators in the input expression. Use two stacks, one to store the operands and one to store the operators. Your program only accpets following operators : ( ) + - / * Write a...
2. Convert the following infix form expression into the postfix form expression by using a stack:...
2. Convert the following infix form expression into the postfix form expression by using a stack: A+(B*(C-D)+E)/F-G*H Show the stack after each push/pop.
Write a Java program which takes a String representing an arithmetic expression as an input and...
Write a Java program which takes a String representing an arithmetic expression as an input and displays whether or not the expression is balanced. If the expression is not balanced (i.e. the wrong # of parentheses or in the wrong order) it will display an error message. For Example: Input an expression: ( ( 2 + 4 ) * 2 ) Expression is balanced Input an expression: ( 5 * 7 – 6 ) ) Error: Expression is not balanced.......
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT