Name: Samira Hussain.
ID: 0182220012101107
Input:
#include <iostream>
#include <stack>
#include <string>
#include <cctype>
using namespace std;
int x = 1; // for t1, t2, ...
int a(char op) {
if (op == '*' || op == '/') return 2;
if (op == '+' || op == '-') return 1;
return 0;
}
string b(string expr) {
string post = "";
stack<char> s;
for (char ch : expr) {
if (ch == ' ') continue;
if (isalnum(ch)) {
post += ch;
} else if (ch == '(') {
s.push(ch);
} else if (ch == ')') {
while (!s.empty() && s.top() != '(') {
post += s.top();
s.pop();
}
if (!s.empty()) s.pop(); // pop '('
} else {
while (!s.empty() && a(s.top()) >= a(ch)) {
post += s.top();
s.pop();
}
s.push(ch);
}
}
while (!s.empty()) {
post += s.top();
s.pop();
}
return post;
}
string temp() {
return "t" + to_string(x++);
}
string c(string post) {
stack<string> s;
for (char ch : post) {
if (isalnum(ch)) {
s.push(string(1, ch));
} else {
string b = s.top(); s.pop();
string a = s.top(); s.pop();
string t = temp();
cout << t << " = " << a << " " << ch << " " << b << endl;
s.push(t);
}
}
return s.top();
}
int main() {
string in;
cout << "Enter an expression like a = b + c - d * e: ";
getline(cin, in);
int p = in.find('=');
if (p == string::npos) {
cout << "Invalid input!" << endl;
return 1;
}
string l = "", r = "";
for (int i = 0; i < p; i++) {
if (!isspace(in[i])) l += in[i];
}
r = in.substr(p + 1);
string post = b(r);
string res = c(post);
cout << l << " = " << res << endl;
return 0;
}
Output: