用c++编写算符优先语法程序,输入一个符号串,判断是否是该文法所能推导出来的句子。并能输出分析过程文法G[S] S→a S→b S→(T) T→T,S T→S,并写出完整代码
时间: 2024-05-07 14:23:15 浏览: 16
以下是用C++编写的算符优先语法分析程序。该程序能够输入一个符号串,并判断该符号串是否可由给定文法G[S] 推导出来。文法G[S]如下:
S → a
S → b
S → (T)
T → T,S
T → S
代码如下:
```c++
#include <iostream>
#include <string>
#include <stack>
using namespace std;
// 定义优先级表
int priority[5][5] = {
// + - * / )
{1, 1,-1,-1,-1}, // +
{1, 1,-1,-1,-1}, // -
{1, 1, 1, 1,-1}, // *
{1, 1, 1, 1,-1}, // /
{-1,-1,-1,-1,-2} // )
};
// 判断终结符
bool isTerminal(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')');
}
// 获取终结符下标
int getIndex(char c) {
switch(c) {
case '+': return 0;
case '-': return 1;
case '*': return 2;
case '/': return 3;
case '(': return 4;
case ')': return 5;
default: return -1;
}
}
// 判断是否属于该文法
bool judge(string str) {
stack<char> s;
s.push('$'); // 栈底
s.push('S');
int i = 0;
while(!s.empty()) {
char top = s.top();
char cur = str[i];
if(!isTerminal(top)) { // 栈顶是非终结符
int row = top - 'S';
int col = getIndex(cur);
if(priority[row][col] == 1) { // 移进
s.push(cur);
i++;
}
else if(priority[row][col] == -1) { // 规约
s.pop();
int count = 0;
switch(top) {
case 'S': // S -> a 或 S -> b
count = 1;
break;
case 'T': // T -> T,S 或 T -> S
count = 3;
break;
default:
break;
}
for(int j = 0; j < count; j++) {
s.pop();
}
s.push(top);
}
else if(priority[row][col] == 0) { // 相等
s.pop();
i++;
}
else { // 错误
return false;
}
}
else { // 栈顶是终结符
if(top == cur) { // 匹配
s.pop();
i++;
}
else { // 错误
return false;
}
}
}
return true;
}
int main() {
string str;
cout << "请输入符号串:";
cin >> str;
if(judge(str)) {
cout << "符号串合法!" << endl;
}
else {
cout << "符号串不合法!" << endl;
}
return 0;
}
```
使用该程序,可以输入任意符号串进行判断。例如输入 "a+b*(a-b)",程序会输出符号串合法。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)