Description
大家都学过了布尔表达式的翻译,其中有一个拉链-回填技术,这次我们就练习这个技术。
Input
输入为一行字符串,例如: a < b or c < d and e < f
每个符号都用空格间隔。
其中逻辑运算符包含 and 和 or , 关系运算符包含 < 、> 、<= 、 >= 、== 、 != 。
Output
假链跳到0,真链跳到1,表达式序号从100开始排。
Sample
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct words{
char op[4];
char left;
char right;
}W;
W s[1000];
int i;
int t = 0;
int count = 100;
int TRUE = 1;
int FALSE = 100;
int cur = 0;
int begin = 0;
char str[1000];
char temp[10];
int main(){
gets(str);
int len = strlen(str);
str[len] = ' ';
str[len+1] = '#';
str[len+2] = '\0';
len = strlen(str);
for(i = 0;i< len;i++){
if(str[i] == ' '){
continue;
}else{
temp[t++] = str[i];
if(str[i] == '#'){
FALSE = 0;
for(;begin<cur-1;begin++){
printf("%d(j%s,%c,%c,%d)\n",count,s[begin].op,s[begin].left,s[begin].right,count+2);
count++;
printf("%d(j,_,_,%d)\n",count,FALSE);
FALSE = count++;
}
printf("%d(j%s,%c,%c,%d)\n",count,s[begin].op,s[begin].left,s[begin].right,TRUE);
TRUE = count++;
printf("%d(j,_,_,%d)\n",count,FALSE);
count++;
t = 0;
temp[t] = '\0';
cur++;
}
if(t==2){
temp[t] = '\0';
if(strcmp("or",temp) == 0){
FALSE +=2;
for(;begin<cur-1;begin++){
printf("%d(j%s,%c,%c,%d)\n",count,s[begin].op,s[begin].left,s[begin].right,count+2);
count++;
printf("%d(j,_,_,%d)\n",count,FALSE);
FALSE = count++;
}
printf("%d(j%s,%c,%c,%d)\n",count,s[begin].op,s[begin].left,s[begin].right,TRUE);
TRUE = count++;
printf("%d(j,_,_,%d)\n",count,FALSE);
count++;
t = 0;
temp[t] = '\0';
begin = cur;
}
}
if(t==3){
temp[t] = '\0';
if(strcmp("and",temp) == 0){
FALSE+=2;
t = 0;
temp[t] = '\0';
}else if(str[i] != '='){
s[cur].left = temp[0];
s[cur].right = temp[2];
temp[0] = temp[1];
temp[1] = '\0';
strcpy(s[cur].op,temp);
t=0;
temp[t] = '\0';
cur++;
}
}
if(t==4){
s[cur].left = temp[0];
s[cur].right = temp[3];
temp[0] = temp[1];
temp[1] = temp[2];
temp[2] = '\0';
strcpy(s[cur].op,temp);
t=0;
temp[t] = '\0';
cur++;
}
}
}
return 0;
}
本人这学期开始学编译原理这门课,做题的时候在网上找到的参考代码几乎都是C++的,所以我打算分享一份C语言版的给朋友们,我只选择了其中一部分题,如果有不会的而且我还没发的,可以私聊我,我们一起讨论