Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

have this but does not work, any help will be appriciated. #include <iostream> #

ID: 3781794 • Letter: H

Question

have this but does not work, any help will be appriciated.

#include <iostream>

#include <stack>

using namespace std;

int prec(char ch) {
if (ch == '*' or ch == '/')
return 2;
else if (ch == '+' or ch == '-')
return 1;
else if (ch == '(' or ch == ')')
return 0;
}

int main() {

char ch;
stack<char> oper;

cin.get(ch);
while (!cin.eof()) {
if((ch>='0' and ch<='9')or
(ch >='a' and ch <'z')or
(ch >'A' and ch <='Z'))
// checking for operand
cout << ch;
else {
if (ch == '(') {
oper.push(ch);
}
else if (ch==')'){
while(!oper.empty() && (oper.top() !='(')) {
cout << oper.top();
oper.pop();
}
if (!oper.empty()) {
oper.pop();
}
else cout << "Error no matching (";
  
}
else if (ch == '*' or ch =='/' or ch == '+' or ch == '-') {
if (oper.empty() or prec(oper.top()) < prec(ch)){
// lower stack has lowest precedence
oper.push(ch);
}   
else {
while (!oper.empty() && prec(oper.top()) >= prec(ch)) {
cout << oper.top();
oper.pop();

}
oper.push(ch);
}
}
else {
cout << " illegal character";
}
cin.get(ch);
}
while (!oper.empty()) {
cout << oper.top();
oper.pop();
}
  
}
}

Explanation / Answer

There are 2 mistakes due to which you got wrong answer :

I have corrected the code. THe corrected code is :

Hope,it helped you.Any other further doubts.Please feel free to ask us.We will love to help you