【发布时间】:2015-01-21 06:41:50
【问题描述】:
编写一个使用以下产生式和动作的解析器(Yacc 和 Lex 文件):
S -> cSS {print “x”}
S -> a {print “y”}
S -> b {print “z”}
表示当输入为cacba时将打印的字符串。
我收到这个错误:当我给它输入时,它说输入有效并且还说语法错误。
我的扫描仪代码是这个
%{
#include "prac.h"
%}
%%
[c] {return C; }
[a] {return A; }
[b] {return B; }
[ \t] ;
\n { return 0; }
. { return yytext[0]; }
%%
int yywrap(void) {
return 1;
}
我的 yacc 代码是这样的:
%{
#include <stdio.h>
%}
%token A B C
%%
statement: S {printf("Valid Input"); }
;
S: C S S {printf("Print x\n");}
| A {printf("Print y\n");}
| B {printf("Print z\n");}
;
%%
int main()
{
return yyparse();
}
yyerror(char *s)
{
printf("\n%s\n",s);
printf("Invalid Input");
fprintf(stderr,"At line %d %s ",s,yylineno);
}
我该如何解决这个问题?
【问题讨论】:
-
你给它什么输入?
-
最好的猜测——你在 Windows 上运行,所以你在导致错误的换行符之前得到一个
\r(回车)字符。尝试将\r添加到[ \t]模式以忽略它。 -
我删除了我的答案,因为它似乎不适合你。仍然将您的
fprintf()语句更改为fprintf(stderr, "At line %d %s", yylineno, s);并不是说它会解决您的问题。 -
@rici 我给它输入 cacba 但它说 syantax 错误
-
@UsamaLucky - 我可以向您发送对我有用的完整代码,遗憾的是,有些人很快就拒绝了 =( 是的,您可以按照我在 lex 中展示的方式使用正则表达式,但是有些人....
标签: regex compiler-construction yacc lex