M - 翻译布尔表达式(C语言版)1
Description
大家都学过了布尔表达式的翻译,其中有一个拉链-回填技术,这次我们就练习这个技术。
Input
输入为一行字符串,例如: a < b or c < d and e < f
每个符号都用空格间隔。
其中逻辑运算符包含 and 和 or , 关系运算符包含 < 、> 、<= 、 >= 、== 、 != 。
Output
假链跳到0,真链跳到1,表达式序号从100开始排。
Sample
input
a<b or c<d and e<f
output
100(j<,a,b,1)
101(j,_,_,102)
102(j<,c,d,104)
103(j,_,_,0)
104(j<,e,f,100)
105(j,_,_,103)
Code
#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;
}
https://blog.csdn.net/qq_43618642/article/details/117135074 ↩︎