fork download
  1. %{
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <math.h>
  5.  
  6. int op = 0, i;
  7. float a, b;
  8.  
  9. // Function prototype
  10. void digi(void);
  11. %}
  12.  
  13. dig [0-9]+|([0-9]*)"."([0-9]+)
  14. add \+
  15. sub \-
  16. mul \*
  17. div /
  18. pow \^
  19. ln \n
  20. %%
  21.  
  22. {dig} { digi(); }
  23.  
  24. {add} { op = 1; }
  25. {sub} { op = 2; }
  26. {mul} { op = 3; }
  27. {div} { op = 4; }
  28. {pow} { op = 5; }
  29.  
  30. {ln} { printf("\nThe result: %f\n\n", a); }
  31.  
  32. [\t ]+ { /* Ignore whitespace */ }
  33.  
  34. . { printf("Unrecognized input: %s\n", yytext); }
  35. %%
  36.  
  37. void digi()
  38. {
  39. if (op == 0)
  40. a = atof(yytext); // Convert to float
  41. else
  42. {
  43. b = atof(yytext);
  44. switch(op)
  45. {
  46. case 1: a = a + b; break;
  47. case 2: a = a - b; break;
  48. case 3: a = a * b; break;
  49. case 4:
  50. if (b != 0)
  51. a = a / b;
  52. else
  53. printf("Error: Division by zero!\n");
  54. break;
  55. case 5:
  56. a = pow(a, b);
  57. break;
  58. }
  59. op = 0;
  60. }
  61. }
  62.  
  63. int main(int argc, char *argv[])
  64. {
  65. yylex();
  66. return 0;
  67. }
  68.  
  69. int yywrap()
  70. {
  71. return 1;
  72. }
  73.  
  74.  
Success #stdin #stdout #stderr 0.03s 6856KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/jZK0tF/prog:2:1: Syntax error: Operator expected
ERROR: /home/jZK0tF/prog:73:0: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit