zoukankan      html  css  js  c++  java
  • 语法分析(16)...

    接下来是这一节的习题 :

    在这个题目中,你将实现一个简单的台式计算器。这个台式计算器的功能像在最后一个讲义中演示的例子一样:即用户可以在控制台上交互输入算术表达式,你的程序判断该表达式是否合法,不合法的话报错并退出运行。

    你的程序涉及表达式的部分要支持如下的表达式:

    E -> n

         | E + E

         | E - E

         | E * E

         | E / E

         | (E)

    其中n是任意的非负整数(注意:在我们演示的例子中,n只是单个字符的整数,所以这个地方你需要做些扩展,这些扩展同时需要涉及修改词法分析yylex函数)。

    以下是代码实现 :

     1 %{
     2 #include <stdio.h>
     3 #include <stdlib.h>
     4     int yylex();
     5     void yyerror(char* err);
     6 %}
     7 /*
     8     "%left '+' '-' '*' '/'
     9 */
    10 
    11 %%
    12 
    13 lines: line
    14      | line lines;
    15 
    16 line: exp '
    ';
    17 
    18 exp: exp '+' term 
    19    | exp '-' term 
    20    | term;
    21     
    22 term: term '*' n
    23     | term '/' n
    24     | n;
    25 
    26 n: '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0' | '(' exp ')';
    27 
    28 %%
    29 
    30 int yylex(){
    31     return getchar();
    32 }
    33 
    34 void yyerror(char* err){
    35     printf("%s
    ", err);
    36 }
    37 
    38 int main (int argc, char* argv[]){
    39     yyparse();
    40     return 0;
    41 }

    结果实例:

    1 [zhangzhimin@ ~] $ bison test.y
    2 [zhangzhimin@ ~] $ gcc test.tab.c 
    3 [zhangzhimin@ ~] $ ./a.out
    4 1+2+3/(3*4-5)+6-7/8
    5 1+
    6 syntax error
    7 [zhangzhimin@ ~] $ 

    感觉这样写难免有点不符合规定投机取巧, 但是说实话不会用yacc, 也不知道yylex分析出来之后的token要怎么表示... 如果以后有时间在深究吧...

  • 相关阅读:
    my first android test
    VVVVVVVVVV
    my first android test
    my first android test
    my first android test
    ini文件
    ZZZZ
    Standard Exception Classes in Python 1.5
    Python Module of the Week Python Module of the Week
    my first android test
  • 原文地址:https://www.cnblogs.com/nzhl/p/5535866.html
Copyright © 2011-2022 走看看