i'm trying to implement a time parser with LEX & YACC. I'm a complete newbie to those tools and C programming.
The program has to print a message (Valid time format 1: input ) when one of those formats is entered: 4pm, 7:38pm, 23:42, 3:16, 3:16am, otherwise a "Invalid character" message is printed.
lex file time.l :
%{
#include <stdio.h>
#include "y.tab.h"
%}
%%
[0-9]+ {yylval=atoi(yytext); return digit;}
"am" { return am;}
"pm" { return pm;}
[ \t\n] ;
[:] { return colon;}
. { printf ("Invalid character\n");}
%%
yacc file time.y:
%{
void yyerror (char *s);
int yylex();
#include <stdio.h>
#include <string.h>
%}
%start time
%token digit
%token am
%token pm
%token colon
%%
time : hour ampm {printf ("Valid time format 1 : %s%s\n ", $1, $2);}
| hour colon minute {printf ("Valid time format 2 : %s:%s\n",$1, $3);}
| hour colon minute ampm {printf ("Valid time format 3 : %s:%s%s\n",$1, $3, $4); }
;
ampm : am {$$ = "am";}
| pm {$$ = "pm";}
;
hour : digit digit {$$ = $1 * 10 + $2;}
| digit { $$ = $1;}
;
minute : digit digit {$$ = $1 * 10 + $2;}
;
%%
int yywrap()
{
return 1;
}
int main (void) {
return yyparse();
}
void yyerror (char *s) {fprintf (stderr, "%s\n", s);}
compiling with this command:
yacc -d time.y && lex time.l && cc lex.yy.c y.tab.c -o time
I'm getting some warnings:
time.y:17:47: warning: format specifies type 'char *' but the argument has type
'YYSTYPE' (aka 'int') [-Wformat]
{printf ("Valid time format 1 : %s%s\n ", (yyvsp[(1) - (2)]), (yyvsp.
This warning appears for all the variables in printf statements.
The values are all char, because even the number in the time string is converted with the atoi
function.
Executing the program with a valid input throws this error:
./time
1pm
[1] 2141 segmentation fault ./time
Can someone help me? Thanks in advance.