c - 识别有效算术表达式以及识别有效标识符和运算符的 Lex 程序

标签 c flex-lexer lex lexer

下面的程序检查像 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();
}

我面临的问题是当我检查 a++b 时它说有效但是当我尝试 a+b- 和其他值如 )a+b(, (a+b(,+a-b++ 它给出我正确的输出。仅对于 a++b 和 a--b 或 a+-b 它失败了。 我有点卡住了。

这是\n 的 if 条件,当我按下 enter 时,我把它放在\n bcz 上,它给我输出并退出。

if(bo==bc && c>d)                   //c>d means if operand is greater than operator
    {  printf("valid exp");  }
      else {  
             printf("invalid exp"); } 

最佳答案

我刚刚将 c=d+1 更改为 c++;产生错误的是一个逻辑错误,而不是检查操作数是否大于我向操作数添加 1 个额外的操作数,并且它总是在 a++b 中评估为 true

%{
#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();
}

关于c - 识别有效算术表达式以及识别有效标识符和运算符的 Lex 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47248897/

相关文章:

c - C中的链表结构与读取txt

c - c程序的内存布局

bison - 弯曲 : input rules are too complicated (>= 32000 NFA states) (while compiling HLA on 62bit)

c++ - YACC/LEX yyparse() 循环问题

c - 获取服务器 ip 0.0.0.0 :0 from getaddrinfo()

c - 弹性 Action 在什么范围内执行?

bison - Lex/Yacc : Print message before input

c - Bison/Yacc 语法中的无意串联

c++ - 为什么 Bison 仍然使用 `int yylex(void)`而找不到 `int yylex(YYSTYPE *yylval_param, YYLTYPE *yylloc_param)`?