我看到很多例子,其中一些将 yytext 传递给 yylval,而另一些则没有。这是 lex 和 yacc 中简单加法器的代码
/* add.l */
digit [0-9]
%%
{digit}+ {sscanf(yytext, "%d", &yylval);
return(INT);
}
\+ return(PLUS);
\n return(NL);
. ;
%%
int yywrap() { return 1; }
Run Code Online (Sandbox Code Playgroud)
和
/* add.y */
/* L = {INT PLUS INT NL} */
%token INT PLUS NL
%%
add: INT PLUS INT NL { printf("%d\n", $1 + $3);}
%%
#include "lex.yy.c"
yyerror(char *s) { printf("%s\n", s); }
main() {
return yyparse();
}
Run Code Online (Sandbox Code Playgroud)
我没有看到像 printf(yylval) 等代码。为什么代码sscanf(yytext, "%d", &yylval) …
这是我的 C 代码:
\n\n#include "stdio.h"\n\nint main()\n{\n int minx, x;\n\n printf("Enter two ints: ");\n scanf( "%d-%d", &minx, &x);\n\n printf("You wrote: minx is %d x is %d", minx, x);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n当输入为5-3或5- 3时,输出为You write: minx is 5 x is 3这是有道理的。但是,当输入为5 -3或5 - 3或6 -4时,输出为You write: minx is 5 x is 8。我期望-跳过空格,所以我期望其他输入的minx为5,x为3、6和4 。-当in%d-%d …