Benny
Benny

Reputation: 498

Fail to continue parsing after correct input

I have two input numbers separated by ','. The program works fine for the first try, but for the second try it always ends with error. How do I keep parsing?

lex file snippet:

 #include "y.tab.h"
%%
[0-9]+ { yylval = atoi(yytext); return NUMBER; }

. return yytext[0];
%%

yacc file snippet:

%{
#include <stdio.h>
int yylex();
int yyerror();
%}
%start s
%token NUMBER
%%
s: NUMBER ',' NUMBER{
            if(($1 % 3 == 0) && ($3 % 2 == 0)) {printf("OK");}
            else{printf("NOT OK, try again.");}
            };
%%
int main(){ return yyparse(); }

int yyerror() { printf("Error Occured.\n"); return 0; }

output snippet:

benjamin@benjamin-VirtualBox:~$ ./ex1 
15,4
OK
15,4
Error Occured.

Upvotes: 0

Views: 211

Answers (1)

rici
rici

Reputation: 241671

Your start rule (indeed, your only rule) is:

s: NUMBER ',' NUMBER

That means that an input consists of a NUMBER, a ',' and another NUMBER.

That's it. After the parser encounters those three things, it expects an end of input indicator, because that's what you've told it a complete input looks like.

If you want to accept multiple lines, each consisting of two numbers separated by a comma, you'll need to write a grammar which describes that input. (And in order to describe the fact that they are lines, you'll probably want to make a newline character a token. Right now, it falls through the the scanner's default rule, because in (f)lex . doesn't match a newline character.) You'll also probably want to include an error production so that your parser doesn't suddenly terminate on the first error.

Alternatively, you could parse your input one line at a time by reading the lines yourself, perhaps using fgets or the Posix-standard getline function, and then passing each line to your scanner using yy_scan_string

Upvotes: 1

Related Questions