刚刚开始学习编译原理,重新开始写一个翻译器,从最简单的开始写一个最简单的例子,将中缀表达式改写成后缀表达式(单个数字)
#includechar lookhead;int main(){ void term(); lookhead=getchar(); term(); while(1) { if(lookhead == '+') { lookhead=getchar(); term(); putchar('+'); } if(lookhead == '-') { lookhead=getchar(); term(); putchar('-'); } } return 0; }void term(){ if(lookhead>='0'&&lookhead<='9') { putchar(lookhead); lookhead=getchar(); } else { printf("error"); }}
改进版
#includechar lookhead;int main(){ char myget(); void term(); void rest(); lookhead=myget(); term(); rest();return 0; }char myget(){ char mylook; mylook = getchar(); for(;;mylook = getchar()) { if(mylook ==' '||mylook =='\t') { ; } else { return mylook; } } }void rest(){ while(1) { if(lookhead == '+') { lookhead=myget(); term(); putchar('+'); putchar(' '); continue; } if(lookhead == '-') { lookhead=myget(); term(); putchar('-'); putchar(' '); continue; } }}void term(){ int n; if(lookhead>='0' && lookhead<='9') { n=0; do { n = n*10 + lookhead - '0'; lookhead=myget(); }while(lookhead >= '0' && lookhead<='9'); printf("%d ",n); } else { printf("error"); }}
改进版2(加入括号和乘除)
#includechar lookhead;int main(){ char myget(); void term(); void factor(); void expr(); lookhead=myget(); factor(); term(); expr();return 0; }char myget(){ char mylook; mylook = getchar(); for(;;mylook = getchar()) { if(mylook ==' '||mylook =='\t') { ; } else { return mylook; } } }void expr(){ if(lookhead == '+') { lookhead=myget(); expr(); term(); putchar('+'); putchar(' '); } if(lookhead == '-') { lookhead=myget(); expr(); term(); putchar('-'); putchar(' '); } term(); }void term(){ if(lookhead == '*') { lookhead=myget(); term(); putchar('*'); putchar(' '); factor(); } if(lookhead == '/') { lookhead=myget(); term(); putchar('/'); putchar(' '); factor(); } factor(); }void factor(){ int n; if(lookhead>='0' && lookhead<='9') { n=0; do { n = n*10 + lookhead - '0'; lookhead=myget(); }while(lookhead >= '0' && lookhead<='9'); printf("%d ",n); } if(lookhead == '(') { lookhead =myget(); do { expr(); }while(lookhead != ')'); lookhead =myget(); }}