A parser program for the following grammar

浪子不回头ぞ 提交于 2019-12-11 06:57:17

问题


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”}  

Indicate the string that it will print when the input is cacba.

I am getting this error: when I give input to it, it says valid input and also says syntax error.

My Scanner Code is this

%{
   #include "prac.h"
%}
%%

[c] {return C; }
[a] {return A; }
[b] {return B;  }
[ \t]   ;
\n  { return 0; }
.   { return yytext[0]; }
%%

int yywrap(void) {
    return 1;
}

And my yacc code is this:

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

How can I fix this?


回答1:


(Comments converted to an answer)

@ChrisDodd wrote:

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 wrote:

Change your fprintf() statement to fprintf(stderr, "At line %d %s", yylineno, s); not that it will solve your problem.

The OP wrote:

You mean I should add \r into \t so the new regex for it will be [\r\t] Am I right ?

@rici wrote:

@chris suggests [ \r\t]. If you have Windows somewhere in the loop, I agree.



来源:https://stackoverflow.com/questions/28061065/a-parser-program-for-the-following-grammar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!