I have been Struggling with this for days... Please HELP! Write a C++ program to
ID: 642807 • Letter: I
Question
I have been Struggling with this for days... Please HELP!
Write a C++ program to read in and evaluate a post fixed expression. The input file is PostFix.dat.
Output: Print out the expression you read in followed by the results of the evaluated expression. The operators you will need to handle are add, subtract and multiply (+, -, * ). The numbers are separated by a blank. You will need to handle multi digit numbers.
Postfix Data file:
5 7 +
52 31 -
3 10 5 - *
13 18 * 140 90 - +
1 2 5 8 5 2 1 + + + + + +
2998 900 - 98 -
4596 4300 96 + - 2 2 * *
55 66 + 17 3 + 20 10 + * +
5 2 * 10 30 * + 6 20 * 60 50 - 20 30 40 + + - + 3 - +
123456 654321 + 123456 654321 + -
99999 30000 *
Explanation / Answer
//Autthor: Cheggexpert
//Date: 03/03/2015
//Theme: Post Fix Exp<b></b>ression Evaluation
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#define MAX 50
using namespace std;
int push(int v);
int top();
int pop(int d);
bool empty();
bool full();
int TOS = 50;
char input[MAX];
int STACK[MAX];
int number1;
int number2;
int main()
{
int i = 0;
int output;
ifstream inputFile;
ofstream outputFile;
inputFile.open("PostFix.txt");
outputFile.open("Evaluation");
cout << "Here are the postfix exp<b></b>ressions. ";
outputFile << "Here are the postfix exp<b></b>ressions. ";
for (int y = 0; y < MAX ; y++)
{
inputFile >> input[y];
cout << input[y] << " ";
outputFile << input[y] << " ";
}
while (input[i] != ' ')
{
if (isdigit(input[i]))
{
int x;
x = input[i] - '0';
push(x);
}
else if((input[i] == '*') || (input[i] == '/') || (input[i] == '-') || (input[i] == '+'))
{
number2 = top(i);
pop(i);
number1 = top(i);
pop(i);
if (input[i] == '+')
{
output = number1 + number2;
}
if (input[i] == '-')
{
output = number1 - number2;
}
if (input[i] == '*')
{
output = number1 * number2;
}
if (input[i] == '/')
{
output = number1 / number2;
}
push(i);
}
i++;
}
cout << " Here are the evaluated results. ";
outputFile << "Here are the evaluated results. ";
for (int y = 0; y < MAX ; y++)
{
cout << output << " ";
outputFile << output << " ";
}
inputFile.close();
outputFile.close();
return 0;
}
int top()
{
if(TOS != MAX)
{
return STACK[TOS];
}
}
int push(int v)
{
if(TOS != full(v))
{
TOS = TOS - 1;
STACK[TOS] = v;
return TOS;
}
else
{
number1 = STACK[++TOS];
}
}
int pop(int d)
{
if(TOS != empty())
{
return -999;
}
else
{
return STACK[TOS--];
}
}
bool empty()
{
if(TOS == MAX)
{
return TOS == MAX;
}
}
bool full()
{
if(TOS == 0)
{
return TOS == 0;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.