40 likes | 239 Views
LEX. Input file: -31 4 54 6 -4 -665 Output file: -31 +4 +54 +6 -4 -665 Total=-636. %{ int total = 0; %} %% [0-9]+ { printf ( " + " ); REJECT;} [+/-]?[0-9]+ {ECHO; total+=atoi ( yytext ); } [ t<br>] {ECHO;} %% int yywrap ( void ) { printf (” Total=%d ”, total ); return 1;
E N D
LEX Input file: -31 4 54 6 -4 -665 Output file: -31 +4 +54 +6 -4 -665 Total=-636 %{ inttotal = 0; %} %% [0-9]+ {printf("+"); REJECT;} [+/-]?[0-9]+ {ECHO; total+=atoi(yytext);} [\ \t\n] {ECHO;} %% intyywrap(void) { printf(”Total=%d”, total); return 1; }
LEX – BEGIN MACRO & TWO STATES Answerthequestion (Y/N): Istheinputcharactersequenceproperlycreatedwithusinglanguagedescribed by regularexpressionanbn, where n>=0 Input file: aaabbb aabbb Output file: aaabbb Y Y aabbb N %{ int a; int b; int OK=1; %} %start aaa %start bbb %% ^a {a=1; BEGIN aaa; ECHO;} <aaa>a {a++; ECHO;} <aaa>b {b=1; BEGIN bbb; ECHO;} <bbb>b {b++; ECHO;} \n {if (OK && a==b) printf(" Y\n"); else printf(" N\n"); a=0; b=0; OK=1;} . {OK=0; ECHO;}
LEX & YACC Ourtaskis to computetotal sum of onlyodddigitsfrominput Input file: 017891 Output file: Total: 18 YACC code: %{ inttot = 0; %} %token oe %start X %% X: A {printf("Total: %d\n", tot);} | A error {yyerror();} ; A: A o{tot += yylval;} | A e | ; %% intyyerror() { printf("Syntax Error!!!\n"); exit(-1); } LEX code: %{ #include "ytab.h" %} %% [02468] {yylval=atoi(yytext);return e;} [13579] {yylval=atoi(yytext);return o;} \n ; . {YY_FATAL("Unexpected character!!!");}