0

当用户输入不完整的定义时,我试图向屏幕显示错误输出,例如:

#define A  // this is wrong , error message should appear

#define A 5 // this is the correct form , no error message would be presented 

但它不起作用,这是代码:

%{
#include <stdio.h>
#include <string.h>
%}

%s FULLCOMMENT
%s LINECOMMENT
%s DEFINE
%s INCLUDE
%s PRINT
%s PSEUDO_C_CODE

STRING [^ \n]*

%%


<FULLCOMMENT>"*/"   {  BEGIN INITIAL; }
<FULLCOMMENT>.      { /* Do Nothing       */ }

<INCLUDE>"<stdio.h>"|"<stdlib.h>"|"<string.h>"  { BEGIN INITIAL;  }
<INCLUDE>.      { printf("error\n");    return 0 ;  }

<DEFINE>[ \t]       {  printf("eat a space within define\n"); } 
<DEFINE>{STRING}    {  printf("eat string %s\n" , yytext);}
<DEFINE>\n      {  printf("eat a break line within define\n"); BEGIN INITIAL; }



"#include"      {   BEGIN INCLUDE;  }
"#define"       {   printf("you gonna to define\n");   BEGIN DEFINE;    }
"#define"+.             {   printf("error\n");  }                                                                                                                                   

%%

int yywrap(void)  { return 1;  }  // Callback at end of file
int main(void)  { 
    yylex(); 
    return 0 ; 
} 

我哪里做错了 ?

这是输出:

a@ubuntu:~/Desktop$ ./a.out
#define A 4
error
A 4
#define A
error
A
4

1 回答 1

1

规则“#define”+。即使输入正确,它也更长并且优先于早期的#define。你可以这样说:-

"#define"[:space:]*$ {printf("error\n"); }

考虑使用带有 flex 的 -dvT 选项来获得详细的调试输出。此外,我不确定您是否需要如此广泛地使用状态来处理除了评论之外的任何事情。但你会更清楚。

于 2012-11-02T10:40:21.973 回答