以下程序检查算术表达式,如a + b a-b,它给输出有效或无效;
%{
#include<stdio.h>
#include<stdlib.h>
int c,d,bo=0,bc=0;
%}
operand [a-zA-Z0-9]+
operator [+\-\/*]
%%
//the operand is one count higher than the operator if that fails then its is invalid eg a+b operand is two and operator is 1;
{operator} {d++;printf("%s is an operator \n",yytext);}
{operand} {c=d+1;printf("%s is an operand \n",yytext);}
"(" {if(bc<=bo)bo++;}
")" {bc++;}
\n {if(bo==bc&&c>d){printf("valid exp");}else {printf("invalid exp");};exit(0);}
%%
void main(){
yylex();
}
我面临的问题是,当我检查一个++ b它说有效但是当我尝试+ b-和其他值如a)a + b(,(a + b(,+ a-b ++)给出我正确的输出。只有a ++ b和a - b或a + -b它才会失败。 我有点卡住了。
这是\ n的if条件,我把它放在\ n bcz当我按下输入它给我输出并退出。
if(bo==bc && c>d) //c>d means if operand is greater than operator
{ printf("valid exp"); }
else {
printf("invalid exp"); }
答案 0 :(得分:1)
我刚刚将c = d + 1改为c ++;这是一个逻辑错误产生错误,而不是检查操作数更大的操作符我添加1额外的操作数,它总是在++ b中评估为真
%{
#include<stdio.h>
#include<stdlib.h>
int c,d,bo=0,bc=0;
%}
operand [a-zA-Z0-9]+
operator [+\-\/*]
%%
//the operand is one count higher than the operator if that fails then its is invalid eg a+b operand is two and operator is 1;
{operator} {d++;printf("%s is an operator \n",yytext);}
{operand} {c++;printf("%s is an operand \n",yytext);}
"(" {if(bc<=bo)bo++;}
")" {bc++;}
\n {if(bo==bc&&c>d){printf("valid exp");}else {printf("invalid exp");};exit(0);}
%%
void main(){
yylex();
}