zoukankan      html  css  js  c++  java
  • flex和bison学习-简易计算器

    flex中的文件 flex1-1.l

    %{
    #include "z.tab.h"
    int yylval;    
    %}
    
    %%
    [0-9]+ { yylval = atoi(yytext); return NUMBER; }
    "+" { return ADD; }
    "-" { return MIN; }
    "*" { return MUL; }
    "/" { return DIV; }
    [ 	]+ { }
    
     { return EOL; }
    . { printf("Error = %c
    ", *yytext); }
    %%

    bison中的文件 bison1-1.y

    %{
    #include <stdio.h>
    int main(int argc, char **argv);
    int yylex();
    void yyerror(const char *s);    
    %}
    
    %token NUMBER;
    %token ADD;
    %token MIN;
    %token MUL;
    %token DIV;
    %token EOL;
    
    %%
    calculater: 
        | calculater exp EOL { $$ = $2; printf("计算结果= %8d
    ", $$); }
        ;
    
    exp: factor
        | exp ADD factor { $$ =  $1 + $3; }
        | exp MIN factor { $$ = $1 - $3; }
        ;
    
    factor: term
        | factor MUL term { $$ = $1 * $3; }
        | factor DIV nozero { $$ = $1 / $3; }
        ;
    
    term: NUMBER
        ;
    
    nozero: NUMBER { $$ = $1 != 0 ? $1 : 1; }
        ;
    %%
    
    int main(int argc, char **argv)
    {
        yyparse();
        return 0;
    }
    
    void yyerror(const char *s) 
    {
        fprintf(stderr, "error = %s
    ", s);
    }

    执行命令:

    bison -d bison1-1.y /* 会生成 bison1-1.tab.h  bison1-1.tab.c */

    flex flex1-1.l /* 会生成 lex.yy.c */

    cc $@ bison1-1.tab.c lex.yy.c -ll -o cal /* $@目标文件 -o要输出的文件 即生成可执行文件 cal */

    ./cal

    注意:

    • flex文件中不需要main函数。
    • flex文件中的yylval要声明,否则会报错
    • bison文件中,flex文件中设计的变量要用%token声明下
    • bison文件中,要对设计到的函数进行声明
    • flex文件是词法分析文件, bison文件中是语法分析文件
  • 相关阅读:
    内置函数zip,map,even
    异常处理
    requests模块(请求接口)
    网络编程之urllib
    cookie/session区别
    测试环境搭建流程
    接口开发01--mock接口
    操作Redis--hash/key-value
    操作excel--xlwt/xlrd/xlutils模块
    可变对象 不可变对象 浅拷贝 深拷贝
  • 原文地址:https://www.cnblogs.com/jisa/p/14570405.html
Copyright © 2011-2022 走看看