-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexp9.cpp
More file actions
77 lines (64 loc) · 2.12 KB
/
exp9.cpp
File metadata and controls
77 lines (64 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
struct Production {
string lhs;
string rhs;
};
int main() {
int num_productions;
cout << "Enter number of productions: ";
cin >> num_productions;
vector<Production> rules(num_productions);
cout << "Enter productions (e.g., S->aSb):" << endl;
for (int i = 0; i < num_productions; ++i) {
string prod;
cin >> prod;
int arrow_pos = prod.find("->");
rules[i].lhs = prod.substr(0, arrow_pos);
rules[i].rhs = prod.substr(arrow_pos + 2);
}
string input;
cout << "Enter input string: ";
cin >> input;
input += "$";
string stack = "$";
string action = "";
cout << "\nLeft align formats:" << left << endl;
cout << setw(20) << "Stack" << setw(20) << "Input" << "Action" << endl;
cout << "------------------------------------------------" << endl;
int i = 0;
while (true) {
cout << setw(20) << stack << setw(20) << input.substr(i) << action << endl;
if (stack == "$" + rules[0].lhs && input[i] == '$') {
cout << setw(20) << stack << setw(20) << "$" << "Accept" << endl;
break;
}
bool reduced = false;
for (const auto& rule : rules) {
if (stack.length() >= rule.rhs.length()) {
string top_of_stack = stack.substr(stack.length() - rule.rhs.length());
if (top_of_stack == rule.rhs) {
stack.erase(stack.length() - rule.rhs.length());
stack += rule.lhs;
action = "Reduce " + rule.lhs + "->" + rule.rhs;
reduced = true;
break;
}
}
}
if (reduced) continue;
// Shift next input symbol onto the stack
if (input[i] != '$') {
stack += input[i];
action = "Shift " + string(1, input[i]);
i++;
} else {
cout << setw(20) << stack << setw(20) << "$" << "Reject (Parsing Error)" << endl;
break;
}
}
return 0;
}