用于以下语法的解析器程序 [英] A parser program for the following grammar
问题描述
编写使用以下生成和操作的解析器(包括Yacc和Lex文件):
Write a parser (both Yacc and Lex files) that uses the following productions and actions:
S -> cSS {print "x"}
S -> a {print "y"}
S -> b {print "z"}
指示当输入<$ c时将打印的字符串$ c> cacba 。
我得到这个错误:当我给它输入,它说有效的输入和语法错误。
I am getting this error: when I give input to it, it says valid input and also says syntax error.
我的扫描程式码是这个
%{
#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);
}
如何解决这个问题?
推荐答案
(转换为回答的评论)
@ChrisDodd写道:
@ChrisDodd wrote:
最好的猜测 - 你运行在windows上,所以你在换行之前得到一个
\r
导致您的错误。尝试将\r
添加到[\t]
模式中以忽略它。
Best guess -- you're running on windows, so you're getting a
\r
(carriage return) character before the newline which is causing your error. Try adding\r
to the[ \t]
pattern to ignore it.
@Cyclone写道:
@Cyclone wrote:
更改
fprintf()语句到
fprintf(stderr,at line%d%s,yylineno,s);
不是说它会解决你的问题。
Change your
fprintf()
statement tofprintf(stderr, "At line %d %s", yylineno, s);
not that it will solve your problem.
OP写道:
您的意思是我应该添加
\r
到\t
,所以新的正则表达式将是<$ c $
You mean I should add
\r
into\t
so the new regex for it will be[\r\t]
Am I right ?
@rici写道:
@chris建议
[\r\t]
。如果你在Windows环境中的某个地方,我同意。
@chris suggests
[ \r\t]
. If you have Windows somewhere in the loop, I agree.
这篇关于用于以下语法的解析器程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!