您的位置:首页 > 其它

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

2018-03-07 19:05 155 查看

北航机试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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: