【发布时间】:2016-02-24 12:51:54
【问题描述】:
我正在尝试使用 LEX 和 YACC 实现时间解析器。 我是那些工具和 C 编程的新手。
当输入以下格式之一时,程序必须打印一条消息(有效时间格式 1:输入):下午 4 点、下午 7:38、23:42、3:16、凌晨 3:16, 否则会打印 “无效字符” 消息。
lex 文件 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 文件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);}
用这个命令编译:
yacc -d time.y && lex time.l && cc lex.yy.c y.tab.c -o time
我收到了一些警告:
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.
对于 printf 语句中的所有变量都会出现此警告。
这些值都是char,因为即使是时间字符串中的数字也是用atoi函数转换的。
使用有效输入执行程序会引发此错误:
./time
1pm
[1] 2141 segmentation fault ./time
有人可以帮助我吗? 提前致谢。
【问题讨论】: