• bison实例


    逆波兰记号计算器【文件名rpcalc.y】

    %{ #define YYSTYPE double #include <stdio.h> #include <math.h> #include <ctype.h> int yylex (void); void yyerror (char const *); %} %token NUM %% input: /* empty */ | input line ; line: ' ' | exp ' ' { printf (" %.10g ", $1); } ; exp: NUM { $$ = $1; } | exp exp '+' { $$ = $1 + $2; } | exp exp '-' { $$ = $1 - $2; } | exp exp '*' { $$ = $1 * $2; } | exp exp '/' { $$ = $1 / $2; } /* Exponentiation */ | exp exp '^' { $$ = pow($1, $2); } /* Unary minus */ | exp 'n' { $$ = -$1; } ; %% #include <ctype.h> int yylex (void) { int c; /* Skip white space. */ while ((c = getchar ()) == ' ' || c == ' ') ; /* Process numbers. */ if (c == '.' || isdigit (c)) { ungetc (c, stdin); scanf ("%lf", &yylval); return NUM; } /* Return end-of-input. */ if (c == EOF) return 0; /* Return a single char. */ return c; } void yyerror (char const *s) { fprintf (stderr, "%s ", s); } int main (void) { return yyparse (); }

    ------------------运行----------------------
    bison rpcalc.y
    gcc -o rpcalc -lm rpcalc.tab.c
    ./rpcalc
    4 9 +
         13
     
    中辍符号计算器【文件名calc.y】

    %{ #define YYSTYPE double #include <math.h> #include <stdio.h> int yylex (void); void yyerror (char const *); %} /* Bison declarations. */ %token NUM %left '-' '+' %left '*' '/' %right '^' /* exponentiation */ %% /* The grammar follows. */ input: | input line ; line: ' ' | exp ' ' { printf (" %.10g ", $1); } ; exp: NUM { $$ = $1; } | exp '+' exp { $$ = $1 + $3; } | exp '-' exp { $$ = $1 - $3; } | exp '*' exp { $$ = $1 * $3; } | exp '/' exp { $$ = $1 / $3; } | '-' exp { $$ = -$2; } | exp '^' exp { $$ = pow ($1, $3); } | '(' exp ')' { $$ = $2; } ; %% #include <ctype.h> int yylex (void) { int c; /* Skip white space. */ while ((c = getchar ()) == ' ' || c == ' ') ; /* Process numbers. */ if (c == '.' || isdigit (c)) { ungetc (c, stdin); scanf ("%lf", &yylval); return NUM; } /* Return end-of-input. */ if (c == EOF) return 0; /* Return a single char. */ return c; } void yyerror (char const *s) { fprintf (stderr, "%s ", s); } int main (void) { return yyparse (); }

    ------------------运行----------------------
    bison calc.y
    gcc -o calc -lm calc.tab.c
    ./calc
    8*(1+3)
         32
  • 相关阅读:
    db2死锁解决
    Cannot create JDBC driver of class '' for connect URL 'null'问题解决
    转 maven 教程一 入门 (http://wentao365.iteye.com/blog/903396)
    db2用户密码不合法
    oracle死锁处理方法
    myeclipse修改jsp页面无反应
    oracle函数方法(虚拟表操作)
    jQuery css选择器 截图
    uwsgi和nginx 使用和配置
    nginx+uwsgi+django部署各模块作用
  • 原文地址:https://www.cnblogs.com/xiaozong/p/6289807.html
Copyright © 2020-2023  润新知