实现一个给定文法的递归下降程序c语言实现

本文介绍了一个简单的文法解析程序,该程序使用递归下降解析器来验证输入字符串是否符合特定的文法规则。文法包括三个非终结符:S, B 和 C,每个非终结符都有对应的产生式。

请添加图片描述

#include <stdio.h>
#include <stdlib.h>

#include <syspes.h>
#include <unistd.h>

/*
要求实现文法
S->aSe
S->B
B->bBe
B->C
C->cCc
C->d
*/


char s[1000];//字符串
int index;//下标
bool ok;

void C(char c){
    if(c=='d') {
        return ;
    }
    else if(c=='c'){
        index++;
        C(s[index]);
        index++;
        if(s[index]!='c') ok=false;
    }
    else ok=false;
}

void B(char c){
    if(c=='c'||c=='d') C(s[index]);
    else if(c=='b') {
        index++;
        B(s[index]);
        index++;
        if(s[index]!='e') ok=false;
    }
    else ok=false;
}

void S(char c){
    if(c=='#') return ;
    else if(c=='b'||c=='c'||c=='d') B(s[index]);
    else if(c=='a'){
        index++;
        S(s[index]);
        index++;
        if(s[index]!='e') ok=false; 
    }
    else ok=false;
}


int main(){
    
    do{
        printf("input an string:(end of #)\n");
        gets(s);//输入一个符号串以#结尾行
        index=0;//更新下标
        ok=true;
        S(s[0]);
        //printf("%d\n",index);

        if(s[index+1]!='#') ok=false;
        if(ok) printf("yes\n");
        else printf("no\n");

    }while(1);
   

    system("pause");
    return 0;
    
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值