北航机试17年02题:词法分析

北航机试17年02题:词法分析

题目:词法分析
描述:输入两行语法正确的C语言语句,第一行是定义变量,第二行是基本C语言表达式,输出第二行中没有在第一行被定义的变量名,如果是数组和指针,只输出数组名或指针名 。
样例:

输入输出
int a,b ,_ x ,_ y,Min,MAx;
result=a+b/2*_x+Min;
result

直接上代码:

/*
北航机试17年03词法分析:
注意C语言命名规则
*/
#include<stdio.h>
#include<string.h>
char name[100][20]; //保存变量名
char output[100][20]; //保存输出变量名
int num, num2; //num 为name中元素个数,num2为output中元素个数
//判断是否为命名字符
bool judge(char c){
    if((c>='0'&&c<='9') || (c>='a'&&c<='z')||(c>='A'&&c<='Z') || (c=='_') ||(c=='$')){
        return true;
    }
    return false;
}
//从变量表中删除出现的变量名,为了防止定义了却没用的情况发生,故增加了output
void delname(char *tmp){
    bool flag=false;
    int i;
    for( i=0;i<num;i++){
        if(strcmp(name[i], tmp)==0){
            flag=true;
            break;
        }
    }
    if(!flag){
        for(i=0;i<num2;i++){
            if(strcmp(output[i], tmp)==0)
                break;
        }
        if(i==num2)
            strcpy(output[num2++], tmp);
    }
}
int main(){
    char c, a[100], tmp[20];
    int i=0, size=0, count=0;
    num=0;
    //输入字符串
    while(scanf("%c", &c)!=EOF && count!=2){
        a[size++]=c;
        if(c==';'){
            count++;
        }
    }
    a[size]=0;
    while(a[i++]!=' ');     //跳过关键字
    int len=0;
    bool flag=false;
    for(;a[i]!='\n';i++){   //不能用a[i]!=';', 会丢失最后一个单词
        if(judge(a[i])){
            tmp[len++]=a[i];
            tmp[len]=0;
            flag=true;
        }else if(flag){
            strcpy(name[num++], tmp);
            len=0;
            flag=false;
        }
    }

    len=0;
    flag=false;
    for(;i<size;i++){        
        if(judge(a[i])){
            tmp[len++]=a[i];
            tmp[len]=0;
            flag=true;
        }else if(flag){
            delname(tmp);
            len=0;
            flag=false;
        }
    }
    //输出
    for(i=0;i<num2;i++){ 
        printf("%s ", output[i]);
    }
    printf("\n");
    return 0;
}   

注:
C语言命名规则:
1. 只能以英文字母、下划线( _ )、美元符号( )线( ) 开 头 。 后 面 可 以 接 数 字 、 英 文 字 母 、 下 划 线 和 美 元 符 号 ( )(可以使用中文,但不推荐使用)
2. 不能是C语言中的关键字。一共有32个关键字, 见下:

auto register unsigned if while static
double int struct break else long switch case enum typedef char extern return union const float short
continue for signed void default goto sizeof volatile do
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值