1
votes

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
What input are you giving it?rici
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.Chris Dodd
I removed my answer since it didn't seem to work for you. Still change your fprintf() statement to fprintf(stderr, "At line %d %s", yylineno, s); not that it will solve your problem.Cyclonecode
@rici I am giving it input cacba but it says syantax erroruser2166164
@UsamaLucky - I can send you the complete code that worked for me, sadly some people are very quick to downvote =( and YES you can use regularexpression in the fashion I showed in lex, but some people ....Cyclonecode

1 Answers

0
votes

(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.