Question

write a program in c++ Read an infix expression from an input file and convert to...

write a program in c++

Read an infix expression from an input file and convert to postfix. Instead of displaying directly on the screen, first place in a queue, and then display the contents of the queue on the screen.

Precondition:

  • The expression will be read from a file (input.txt) that contains a single line. There will be no spaces between the operands and the operators.
  • The following operators are allowed: ( ) + - * /
    • The normal rules of precedence will apply.
  • No error checking is necessary.
  • The numbers will all be greater than 0 and less than 10 (positive, single digit numbers)

Example:

1+2

converts to

12+

0 0
Add a comment Improve this question Transcribed image text
Answer #1

INPUT

##########

Input to the program is a text file "input.txt" as shown in the screenshot below

########################### PGM START ###################################

#include<bits/stdc++.h>
#include<fstream>

using namespace std;


#define SIZE 100

//********************** Stack implementation
class Stack

{
    int top;
public:
    char a[SIZE];  


    Stack(){
       //initialising top of stack as -1
       //which measn empty stack
       top = -1;
   }

   //function declaration
    bool push(char x);
    char pop();
    bool isEmpty();
    char topElement();
};

//function to push character into stack
bool Stack::push(char x)
{

   //checking the overflow condition in the stack
    if (top >= (SIZE-1))
    {

        cout << "Stack Overflow";
        return false;
    }
    else
    {

       //pushing element to stack
        a[++top] = x;
        return true;
    }
}

//returns the first top elemnt of the stack
char Stack::topElement()
{
    if (top < 0)
    {

        cout << "empty Stack";
        return 'N';
    }
    else
    {

        char x = a[top];
        return x;
    }
}

//pop() remove the top element from stack
char Stack::pop()
{
    if (top < 0)
    {
        cout << "Stack Underflow";
        return 'N';
    }

    else
    {
        char x = a[top--];
        return x;
    }
}

//isEmpty() checks if stack is empty or not
bool Stack::isEmpty()
{
    return (top < 0);
}

//**************************** Queue Implementation
class Queue
{
    int front,rear;
public:
    char a[SIZE];  


    Queue(){
       rear=-1;
       front=0;
   }

   //function declaration
    bool enqueue(char x);
    char dequeue();
    bool isEmpty();
};

bool Queue::enqueue(char x)
{

   //checking the overflow condition for queue
    if (rear >= (SIZE-1))
    {

        cout << "Queue Overflow";
        return false;
    }
    else
    {

       //inserting element to queue
        a[++rear] = x;
        return true;
    }
}

//dequeue() remove the front element from queue
char Queue::dequeue()
{
    if (rear < 0)
    {
        cout << "Queue Underflow";
        return 'N';
    }
    else

    {
        char x = a[front++];
        return x;
    }
}

//isEmpty() checks if queue is empty or not
bool Queue::isEmpty()
{
    return (front>rear);
}

//************************Infix to postfix conversion ***
//Function to return precedence of operators
int precedenceValue(char c){
    if(c == '*' || c == '/')
       return 2;

   else if(c == '+' || c == '-')
       return 1;
    else
       return -1;
}

/*
infixToPostfix() function converts infix expression
to postfix expression
*/
void infixToPostfix(string s)
{
    Stack st;
    Queue q;

    int l = s.length();
    string finalString;
    for(int i = 0; i < l; i++)
    {

        // If the character is an operand, append it to queue
       if((s[i] >= '0' && s[i] <= '9'))
           q.enqueue(s[i]);


        // If the character is an ‘(‘, push it to the stack.
        else if(s[i] == '(')
            st.push('(');

       
        // If the character is an ‘)’, pop and to output string from the stack
        // until an ‘(‘ is seen
        else if(s[i] == ')'){
            while(!st.isEmpty() && st.topElement() != '(')
            {
                char c = st.topElement();
                st.pop();

                q.enqueue(c);
            }
            if(st.topElement() == '(')
            {

                char c = st.topElement();
                st.pop();
            }
        }

        //If an operator is scanned, if the precedence of current operator is less than one in stack
        //pop th eoperator in stack and enqueue i to queue
        //else push the operator to stack
        else{
            while(!st.isEmpty() && precedenceValue(s[i]) <= precedenceValue(st.topElement())){
                char c = st.topElement();
                st.pop();
                 q.enqueue(c);

            }
            st.push(s[i]);
        }

    }

    //Pop all the remaining elements from the stack
    //enqueue it to queue
    while(!st.isEmpty())
   {
        char c = st.topElement();
        st.pop();
         q.enqueue(c);
    }

  
    //removing elements one by one from queue to get final string
   while(!q.isEmpty()){
       finalString+=q.dequeue();
   }
   
    cout <<"Postfix Notation = "<< finalString << endl;

}


// Driver program to test above functions
int main()
{
   string s;

  
   //reading the infix expression from input.txt file
   //file have only one line
   fstream infile;
   infile.open("input.txt");

  
   //storing the line read into string s
   getline(infile,s);
   cout<<"Infix Expression = "<<s<<"\n";

  
   //calling infixto postfix conversion function
   infixToPostfix(s);

    return 0;
}

################################ PGM END #################################

Output Screenshot

#################

Add a comment
Know the answer?
Add Answer to:
write a program in c++ Read an infix expression from an input file and convert to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • implement a class of infix calculators (Using C++). Consider a simple infix expression that consist of...

    implement a class of infix calculators (Using C++). Consider a simple infix expression that consist of single digit operands; the operators +, -, *, and / ; and parentheses. Assume that unary operators are illegal and that the expression contains no embedded spaces. Design and implement a class of infix calculators. Use the algorithms given in the chapter 6 to evaluate infix expressions as entered into the calculator. You must first convert the infix expression to postfix form and then...

  • In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an...

    In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers For Example: Infix expression (6 + 2) * 5 - 8 / 4 to a postfix expression is  62+5*84/- The program should read the expression into character array infix and use the stack functions implemented in this chapter to help create the postfix expression in character array postfix. The...

  • Total point: 15 Introduction: For this assignment you have to write a c program that will...

    Total point: 15 Introduction: For this assignment you have to write a c program that will take an infix expression as input and display the postfix expression of the input. After converting the postfix expression, the program should evaluate the expression from the postfix and display the result. What should you submit? Write all the code in a single file and upload the .c file. Problem We as humans write math expression in infix notation, e.g. 5 + 2 (the...

  • Write a java program for the following: Your program reads an infix expression represented by a...

    Write a java program for the following: Your program reads an infix expression represented by a string S from the standard input (the keyboard). Then your program converts the infix expression into a postfix expression P using the algorithm. Next, your program evaluates the postfix expression P to produce a single result R. At last, your program displays the original infix expression S, the corresponding postfix expression P and the final result R on the standard output ( the screen...

  • You are to write a program name expressionTree.java that evaluates an infix expression entered by the...

    You are to write a program name expressionTree.java that evaluates an infix expression entered by the user. The expression may contain the following tokens: (1) Integer constants (a series of decimal digits). (2)   One alphabetic character - "x" (representing a value to be supplied later). (3)   Binary operators (+, -, *, / and % (modulo)). (4)   Parentheses          You will parse the input expression creating an expression tree with the tokens, then use the postOrder tree traversal algorithm to extract...

  • Develop an Expression Manager that can do the following operations: Balanced Symbols Check • Read a...

    Develop an Expression Manager that can do the following operations: Balanced Symbols Check • Read a mathematical expression from the user. • Check and report whether the expression is balanced. • {, }, (, ), [, ] are the only symbols considered for the check. All other characters can be ignored. Infix to Postfix Conversion • Read an infix expression from the user. • Perform the Balanced Parentheses Check on the expression read. • If the expression fails the Balanced...

  • Write a java program to convert and print an infix expression to postfix expression. You can...

    Write a java program to convert and print an infix expression to postfix expression. You can use Java stack methods. (Must read input from System.in) Your main method should be as follow: public static void main(String args[]) { intopost p = new intopost (); String iexp, pexp; //infix postfix expression             try{ Scanner inf = new Scanner (System.in);                     // Read input from KB/ File while(inf.hasNext()){ // read next infix expression                                 iexp = inf.next(); // Assume method name to convert infix...

  • For this project you will implement a simple calculator. Your calculator is going to parse infix...

    For this project you will implement a simple calculator. Your calculator is going to parse infix algebraic expressions, create the corresponding postfix expressions and then evaluate the postfix expressions. The operators it recognizes are: +, -, * and /. The operands are integers. Your program will either evaluate individual expressions or read from an input file that contains a sequence of infix expressions (one expression per line). When reading from an input file, the output will consist of two files:...

  • Stacks are used by compilers to help in the process of evaluating expressions and generating machine...

    Stacks are used by compilers to help in the process of evaluating expressions and generating machine language code.In this exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses. Humans generally write expressions like 3 + 4and 7 / 9in which the operator (+ or / here) is written between its operands—this is called infix notation. Computers “prefer” postfix notation in which the operator is written to the right of its two operands. The preceding...

  • We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are...

    We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are written in-between the operands). In a computer’s language, however, it is preferred to have the operators on the right side of the operands, i.e. 5 2 +. For more complex expressions that include parenthesis and multiple operators, a compiler has to convert the expression into postfix first and then evaluate the resulting postfix. Write a program that takes an “infix” expression as input, uses...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT