****C++ program that uses a single stack that will read postfix expressions and
ID: 3703714 • Letter: #
Question
****C++ program that uses a single stack that will read postfix expressions and prints their values. WITH COMMENTS ON ECH LINE
Each input expression will be on its own line as shown in the fix.txt file.
The output of each expression should be displayed
The program should terminate when the end of the file
Assume only binary operators and that the expression contain no variables.
Note that you will need to use parentheses to indicate the order of application of the operators in the expression. For example:
Explanation / Answer
#include<iostream>
#include<stack>
#include <fstream>
#include <string>
using namespace std;
bool IsDigit(char data)
{
if(data >= '0' && data <= '9')
{
return true;
}
return false;
}
bool IsOperator(char data)
{
if(data == '+' || data == '-' || data == '*' ||data == '/')
{
return true;
}
return false;
}
int executeOperation(char operation, int operand1, int operand2)
{
if(operation == '+')
{
return operand1 +operand2;
}
else if(operation == '-')
{
return operand1 - operand2;
}
else if(operation == '*')
{
return operand1 * operand2;
}
else if(operation == '/')
{
return operand1 / operand2;
}
else
{
cout<<"Not a operand error ";
}
return -1;
}
int EvaluatePostfix(string expression)
{
stack<int> Sdata;
for(int i = 0;i< expression.length();i++) {
if(expression[i] == ' ' || expression[i] == ',')
{
continue;
}
else if(IsOperator(expression[i])) {
int operand2 = Sdata.top();
Sdata.pop();
int operand1 = Sdata.top();
Sdata.pop();
int result = executeOperation(expression[i], operand1, operand2);
Sdata.push(result);
}
else if(IsDigit(expression[i])){
int operand = 0;
while(i<expression.length() && IsDigit(expression[i])) {
operand = (operand*10) + (expression[i] - '0');
i++;
}
i--;
Sdata.push(operand);
}
}
return Sdata.top();
}
int main() {
int value=0 ;
string line;
ifstream myFile;
myFile.open("postfix.txt");
if (myFile.is_open()) {
while (!myFile.eof())
{
getline (myFile,line);
cout<<"Input is "<<line<<endl;
value= EvaluatePostfix(line);
cout<<"Output is "<<value<<endl;
}
cout<<endl;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.