2. Write a C++ program that reads string expressions from input file “expressions.txt”. The program should check if the given postfix expression is valid
It is not necessary to solve the string, and you can use a counter, not a stack.
The counter tracks the number of values that would be on the stack if you would have solved the expression.
let's consider you have only operands and binary operators.
This algorithm uses a special decreament operation: if when you decrement, the counter goes below zero, the string is invalid:
C++ code:-
#include<iostream>
using namespace std;
//this utility function checks if count < 0, then return
true
bool checkCount(int count)
{
if(count < 0)
{
cout << "\nPostfix expression
in Invalid" << endl;
true;
}
return false;
}
int main()
{
//redding postfix expression
string postfix;
cout << "Enter Postfix expression: ";
cin >> postfix;
//initialis the counter
int count = 0;
//looping through each character in exp
for(int i = 0 ; i < postfix.size() ; i++)
{
//if we find a binary
operator
if(postfix[i] == '+' || postfix[i]
== '-' ||
postfix[i] == '*' || postfix[i] == '/' ||
postfix[i] == '^')
{
//decreament the
cound
//this simulates
popping from the stack.
//while solving
we pop twixw from stack if an operator is found
count--;
count--;
if(checkCount(count))
{
cout << "\nPostfix expression in Invalid"
<< endl;
return 0;
}
//now
increasing
//after popping
in prevoius step, we need to evaluate the exp
//and the result
is pushed in stack
//so we
increament
count ++;
}
//if any upper case or lower case
character
//that is we have an english
letter
//considering that as an
operand
else if( isupper(postfix[i]) ||
islower(postfix[i]))
{
count++;
}
else
{
cout <<
"\nPostfix expression in Invalid" << endl;
return 2;
}
}
//if count == 1
//the stack only has a single value
//the result
if(count == 1)
cout <<"\nPostfix Expression
is valid.";
else
cout << "\nPostfix expression
in Invalid" << endl;
return 0;
}


2. Write a C++ program that reads string expressions from input file “expressions.txt”. The program should...