对于这个文法 S-> +SS | *SS | a,用c语言实现递归下降语法分析,合法的输入串输出“Yes”;不合法的输出“No”,并输出错误位置信息,在每次推导时输出文法信息
时间: 2024-02-05 15:12:46 浏览: 24
以下是使用C语言实现递归下降语法分析的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[100]; // 存储输入串
int index = 0; // 输入串索引
void S();
void error(char *msg);
int main() {
printf("请输入一个输入串:");
scanf("%s", input);
S();
if (input[index] == '\0') {
printf("Yes\n");
} else {
printf("No,错误位置:%d\n", index + 1); // 索引从0开始,输出时要加1
}
return 0;
}
// 分析S的函数
void S() {
if (input[index] == '+') {
printf("S -> +SS\n");
index++;
S();
S();
} else if (input[index] == '*') {
printf("S -> *SS\n");
index++;
S();
S();
} else if (input[index] == 'a') {
printf("S -> a\n");
index++;
} else {
error("不合法的输入");
}
}
// 输出错误信息并退出程序
void error(char *msg) {
printf("No,%s,错误位置:%d\n", msg, index + 1);
exit(0);
}
```
我们通过递归函数S()来分析输入串。每次调用S()时,判断输入串中index位置的字符,如果是+或*则按照文法S->+SS和S->*SS进行推导,调用两次S()函数;如果是a则按照文法S->a进行推导,index加1;如果不是+、*、a中的任意一个字符则输出错误信息并退出程序。
在每次推导时,我们输出对应的文法信息。最后判断输入串是否被完全分析,如果没有则输出错误信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)