繁体   English   中英

以下语法的解析器程序

[英]A parser program for the following grammar

编写一个解析器(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);
}

我怎样才能解决这个问题?

评论转换为答案

@ChrisDodd写道:

最好的猜测-您正在Windows上运行,因此在换行之前会出现\\r (回车)字符,这会导致您的错误。 尝试将\\r添加到[ \\t]模式以忽略它。

@旋风写道:

将您的fprintf()语句更改为fprintf(stderr, "At line %d %s", yylineno, s); 不是说它将解决您的问题。

OP写道:

您的意思是我应该将\\r添加到\\t因此新的正则表达式将为[\\r\\t]是吗?

@rici写道:

@chris建议[ \\r\\t] 如果您有Windows出现在循环中,我同意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM