0% found this document useful (0 votes)
28 views3 pages

Input: Name: Samira Hussain. ID: 0182220012101107

Uploaded by

shaikatpaul98
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views3 pages

Input: Name: Samira Hussain. ID: 0182220012101107

Uploaded by

shaikatpaul98
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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:

You might also like