Question

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: postfix.txt that contains the corresponding postfix expressions one per line and results.txt that contains their evaluation, also one per line.

An example of an infix expression is the following:
( 12 + 3 ) * ( 9 – 74 ) + 34 / ( ( 85 – 93 ) + ( 3 + 5 ) * 3 ) - 5

It is guaranteed to:
• Contain only integers
• Contain only round parentheses
• All operands and operators are separated by a single space

A malformed expression may however:
• Have unbalanced parentheses — e.g. ( ( ( 3 + 2 )
• Have operators other than the expected ones — e.g 2 ^ 3

Your program will parse the infix expression from left to right, identify the operands, the operators and the parentheses and ignore blanks. You will implement the infix to postfix conversion algorithm using a stack of operators and parentheses. You can use the STL stack (#include )

Your program should handle syntactically malformed infix expressions using exceptions (you can use the PrecondViolatedExcep class used with the List class — see Project4). When an exception occurs, the exception message should be written to the postfix file and results file instead of the respective postfix expression and result. For unbalanced parenthesis the message must be: “Precondition Violated Exception: Unbalanced parenthesis” For unknown operator the message must be: “Precondition Violated Exception: Unknown operator”

Implementation:

You will implement the calculator as a class named PostfixCalculator.
You may design this class as you wish, but it MUST have the following public methods:
• A default constructor
• std::string convertToPostfix(std::string infix_expression);

Takes a string representation of the infix expression, parses it into the corresponding postfix expression and returns the postfix expression as a string. In the string representation of the postfix expression, operands and operators are also separated by a single space. For example a valid postfix expression string corresponding to infix “3 - (137 + 76)” would be: “3 134 76 + -“

Note that there are no parentheses in the output postfix expression.
If the input expression is malformed (i.e. unbalanced parenthesis or unknown operator) this function will throw a PrecondViolatedExcept exception with the corresponding error message as described above.
When we described the algorithm in lecture, we did not consider the fact that, without parenthesis, * and / have higher precedence than + and - and your calculator will need to take that into account.
On Blackboard under Course Materials/Project7 you will find pseudocode for parsing infix to postfix from your textbook that takes precedence into account. Your textbook uses peek() instead of top() for retrieving the element at the top of the stack.

double calculatePostfix(std::string postfix_expression);
takes a string representation of the postfix expression (in the format described above), calculates the result and returns it. It assumes that the postfix expression is well formed (don’t forget to specify all pre and post conditions as well s inputs and outputs in your comment preambles)

void testCalculator(std::string input_file_name); will implement the file input/output behavior described above: Read every infix expression from the input file and:

• Convert it to postfix (don’t forget to do this in a try-catch block, convertToPostfix may throw an exception!)

  • Write the corresponding postfix expression into postfix.txt, but if convertToPostfix throws and exception, write the error message instead
  • Evaluate the postfix expression if wellformed and write the result in results.txt, otherwise write the error message there too

All data is on a new line, so if the input file is:

input.txt is:

(2+3)
( ( 3 + 4
(5 + 3) * 2

postfix.txt is:

23+
Precondition Violated Exception: Unbalanced parenthesis

53+2*

results.txt is

5

Precondition Violated Exception: Unbalanced parenthesis

16

You may add as many private functions and data members as necessary.

Review: Writing output:

Writing to an output file is similar to reading from one and is done using Similarly to what we have done with ifstream, you can declare an ofstream object, you open it and close it like you do for a ifstream, and you can write to it as you do with the standard output stream using the << operator.

Thus, if you declare an ofstream object out_file: out_file.open(“results.txt”);

out_file << 4.5 << “/n”;

writes the number 4.5 to results.txt followed by a new line out_file.close(); will close the stream.

Standard Template Library (STL):

You can use the Standard Template Library for this project, in particular . C++ Interlude 8 in your textbook gives an overview of the STL. You should start familiarizing with containers/adapters and algorithms in the STL as you learn about them. There are also many references and tutorials online.
You don’t need to overwhelm yourself, you can look-for-and-learn as you need, but it is good to know what is there so you’ll know to look for it.
Also, you should familiarize with the STL equivalent of what you are learning
- Vector
- List (in STL list is doubly-linked, forward-list is singly-linked)
- Stack
- Queue
Be aware of other containers so you will know to look for them when you need them. Be aware of what is available to you in
Understand iterators
Explore and have fun!!!

Testing:

Come up with infix expressions and test them individually. Some correct, some with unbalanced parenthesis (both opening-unbalanced and closing-unbalanced) and with unknown operators. Make sure your output is as specified above.

Once you have tested the functions individually, create an input file with all the examples you came up with, and make sure you are correctly writing the output files postfix.txt and results.txt.

#include "PrecondViolatedExcep.hpp"
PrecondViolatedExcep::PrecondViolatedExcep(const std::string& message):std::logic_error("Precondition Violated Exception: " + message)
{
}  // end constructor
// End of implementation file.

#ifndef PRECOND_VIOLATED_EXCEP_
#define PRECOND_VIOLATED_EXCEP_

#include <stdexcept>
#include <string>

class PrecondViolatedExcep : public std::logic_error
{
public:
PrecondViolatedExcep(const std::string& message = "");
}; // end PrecondViolatedExcep
#endif


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

Help input - Notepad File Edit Format View |(2+3) ((3+4 (5+3)*2 In 1, Col1 100results - Notepad File Edit Format View Help Precondition Violated Exception: Unbalanced parenthesispostfix - Notepad File Edit Format View 23+ Help Precondition Violated Exception: Unbalanced parenthesis 53+2*

//Code here


#include<iostream>
#include<string>
#include <sstream>
#include <cstdlib>
#include <fstream>
using namespace std;

template <class X>
class Stack
{
   X *stackData;
   int currentIndex;
   int size;

public:

   Stack(int size = 20);
   void push(X);
   X pop();
   X top();

   int getSize();
   bool isEmpty();
   bool isFull();

   void display();
};
template <class X>
Stack<X>::Stack(int size)
{
   stackData = new X[size];
   this->size = size;
   currentIndex = -1;
}

template <class X>
void Stack<X>::push(X data)
{
   if (!isFull())
   {
       stackData[++currentIndex] = data;
   }

}

template <class X>
X Stack<X>::pop()
{
   if (!isEmpty())
   {
       return stackData[currentIndex--];
   }
}
template <class X>
X Stack<X>::top()
{
   if (!isEmpty())
       return stackData[currentIndex];
}

template <class X>
int Stack<X>::getSize()
{
   return size;
}
template <class X>
bool Stack<X>::isEmpty()
{
   return currentIndex == -1;
}

template <class X>
bool Stack<X>::isFull()
{
   return currentIndex == size - 1;
}

template <class X>
void Stack<X>::display(){
   if (currentIndex>-1)
   {
       cout << "Data : \n\t";
       for (int i = 0; i <= currentIndex; i++)
           cout << stackData[i] << " ";
       cout << "\n";
   }
   else
   {
       cout << "Stack is Empty\n";
   }
}
bool isBalncePranthesis(string expression, Stack<char> stack){
   char character;
   for (int i = 0; i < expression.length(); i++)
   {
       if ((expression[i] == '(') || (expression[i] == '{') || (expression[i] == '['))
       {
           stack.push(expression[i]);
       }
       if ((stack.isEmpty()))
       {
           return false;
       }
       switch (expression[i])
       {
       case ')':
           character = stack.top();
           stack.pop();
           if (character == '[' || character == '{')
               return false;
           break;
       case '}':
           character = stack.top();
           stack.pop();
           if (character == '[' || character == '(')
               return false;
           break;
       case ']':
           character = stack.top();
           stack.pop();
           if (character == '(' || character == '{')
               return false;
           break;
       default:
           break;
       }
   }
   return stack.isEmpty();
}
bool string_Checking(string str){
   string copyGenrate = "";
   int count = 0;
   for (int i = 0; i < str.length(); i++)
   {
       if ((str[i] == '(') || (str[i] == ')') || (str[i] == '{') || (str[i] == '}') || (str[i] == '[') || (str[i] == ']'))
       {
           copyGenrate = copyGenrate + str[i];
       }
   }
   Stack<char> stack(copyGenrate.length());
   if (copyGenrate != "")
   if (isBalncePranthesis(copyGenrate, stack)){
   return 1; //   cout << "\tAccepted: Sequence is right\n";
   }
   else
       return 0;//cout << "\tError: Wrong Sequence\n";
   else
       return 0;//cout << "\tYour Input is WithOut Prentheises \n";
}
//--------------------------------(Functions)--------------------------------------
bool IsOperand(char character)
{
   if (character >= '0' && character <= '9') return true;
   return false;
}
bool IsOperator(char character)
{
   if (character == '+' || character == '-' || character == '*' || character == '/'||character=='%')
       return true;
   return false;
}
int GetOperatorPresidency(char op)
{
   int presidency = 0;
   switch (op)
   {
   case '+':
   case '-':
       presidency = 1;
       break;
   case '*':
   case '/':
   case '%':
       presidency = 2;
       break;
   }
   return presidency;
}
float Result(char Operator, float firstValue, float secondValue){
   switch (Operator)
   {
   case '+':
       return float(firstValue) + float(secondValue);
   case '-':
       return float(firstValue) - float(secondValue);
   case '/':
       return float(firstValue) / float(secondValue);
   case '*':
       return float(firstValue) * float(secondValue);
   default:
       break;
   }
}
int HasHigherPrecedence(char op1, char op2)
{
   int op1Weight = GetOperatorPresidency(op1);
   int op2Weight = GetOperatorPresidency(op2);

   if (op1Weight == op2Weight)
       return true;
   return op1Weight > op2Weight ? true : false;
}
string InToPostfix(string expression, Stack<char> stack){
   string postfix = "";
   for (int i = 0; i< expression.length(); i++) {
       if (IsOperator(expression[i]))
       {
           while (!stack.isEmpty() && stack.top() != '(' && HasHigherPrecedence(stack.top(), expression[i]))
           {
               postfix += stack.top();
               stack.pop();
           }
           stack.push(expression[i]);
       }
       else if (IsOperand(expression[i]))
       {
           postfix += expression[i];
       }
       else if (expression[i] == '(')
       {
           stack.push(expression[i]);
       }
       else if (expression[i] == ')')
       {
           while (!stack.isEmpty() && stack.top() != '(') {
               postfix += stack.top();
               stack.pop();
           }
           stack.pop();
       }
   }
   while (!stack.isEmpty()) {
       postfix += stack.top();
       stack.pop();
   }
   return postfix;
}
int StringToInt(string data){

   stringstream converter(data);

   int Integer = 0;
   converter >> Integer;

   return Integer;
}
float calculateExperassion(string expression){
   Stack<char> charStack(expression.length());
   Stack<float> intStack(expression.length());
   float firstValue, secondValue; char Operater;
   float answer = 0;
   string intValue = "";
   for (int i = 0; i < expression.length(); i++) {
       if (IsOperator(expression[i]))
       {

           if (intValue != "")
           {
               intStack.push(StringToInt(intValue));
               intValue = "";
           }
           while (!charStack.isEmpty() && charStack.top() != '(' && HasHigherPrecedence(charStack.top(), expression[i]))
           {
               Operater = charStack.pop();
               secondValue = intStack.pop();
               firstValue = intStack.pop();
               intStack.push(Result(Operater, firstValue, secondValue));
           }
           charStack.push(expression[i]);

       }
       if (IsOperand(expression[i]))
       {
           intValue = intValue + expression[i];

       }
       if (expression[i] == '(')
       {
           if (intValue != "")
           {
               intStack.push(StringToInt(intValue));
               intValue = "";
           }
           charStack.push(expression[i]);
       }
       if (expression[i] == ')')
       {
           if (intValue != "")
           {
               intStack.push(StringToInt(intValue));
               intValue = "";
           }
           while (!charStack.isEmpty() && charStack.top() != '(') {

               Operater = charStack.pop();
               secondValue = intStack.pop();
               firstValue = intStack.pop();
               intStack.push(Result(Operater, firstValue, secondValue));
           }
           charStack.pop();
       }
   }
   if (intValue != "")
       intStack.push(StringToInt(intValue));
   while (!charStack.isEmpty()) {

       Operater = charStack.pop();
       secondValue = intStack.pop();
       firstValue = intStack.pop();
       intStack.push(Result(Operater, firstValue, secondValue));
   }
   return answer = intStack.pop();
}
//-----------------------------------------------------------------------
string ConvertionToPostFix(string expression){
   Stack<char> stack(expression.length());
   return (InToPostfix(expression,stack));
}

int main(){
   ifstream inFile;
ofstream file;
ofstream file1("postfix.txt", ios::out | ios::app);
ofstream file2("results.txt", ios::out | ios::app);
inFile.open(".\\input.txt");
if (inFile.fail()) {
cout << "Error opening a file" << endl;
inFile.close();
}
string line;
while (getline(inFile, line))
{
if(string_Checking(line)){
   file1<<ConvertionToPostFix(line)<<"\n";
   file2<<calculateExperassion(line)<<"\n";
   }
   else{
   file1<<"Precondition Violated Exception: Unbalanced parenthesis\n";
   file2<<"Precondition Violated Exception: Unbalanced parenthesis\n";
   }
}
inFile.close();
ofile << inFile.rdbuf();
file.open("input.txt");
   return 0;
}

//if you have any query contact me

Add a comment
Know the answer?
Add Answer to:
For this project you will implement a simple calculator. Your calculator is going to parse infix...
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...

  • 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...

  • 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...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • 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...

  • 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...

  • 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...

  • C++: Learning Outcomes Implement two stacks and use them to implement an infix to prefix expression...

    C++: Learning Outcomes Implement two stacks and use them to implement an infix to prefix expression convertor Stacks A stack is an abstract data type which uses a sequential container and limits access to that container to one end. You may enter or remove from the container, but only at one end. Using the Linked List data structure from your last homework assignment, implement a Stack of type string. The Stack should only have one data member: the Linked List....

  • EVALUATING GENERAL INFIX EXPRESSIONS INTRODUCTION The notation in which we usually write arithmetic expressions is called infix notation;...

    EVALUATING GENERAL INFIX EXPRESSIONS INTRODUCTION The notation in which we usually write arithmetic expressions is called infix notation; in it, operators are written between their operands: X + Y. Such expressions can be ambiguous; do we add or multiply first in the expression 5 + 3 * 2? Parentheses and rules of precedence and association clarify such ambiguities: multiplication and division take precedence over addition and subtraction, and operators associate from left to right. This project implements and exercises a stack-based algorithm that evaluates...

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