fork download
  1. %{
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <math.h>
  5.  
  6. int op = 0;
  7. float a, b;
  8. %}
  9.  
  10. %option noyywrap
  11.  
  12. /* Regular Expressions Section */
  13. dig [0-9]+(\.[0-9]+)? /* Match numbers including decimals */
  14. add "+" /* Match addition operator */
  15. sub "-" /* Match subtraction operator */
  16. mul "*" /* Match multiplication operator */
  17. div "/" /* Match division operator */
  18. pow "^" /* Match exponentiation operator */
  19. ln \n /* Match newline to print result */
  20.  
  21. /* Rules Section */
  22. %%
  23. {dig} {digi();} /* Process numbers */
  24. {add} {op=1;} /* Set operation to addition */
  25. {sub} {op=2;} /* Set operation to subtraction */
  26. {mul} {op=3;} /* Set operation to multiplication */
  27. {div} {op=4;} /* Set operation to division */
  28. {pow} {op=5;} /* Set operation to exponentiation */
  29. {ln} {printf("\nThe Answer: %f\n\n", a);} /* Print result on new line */
  30.  
  31. /* C Code Section */
  32. %%
  33.  
  34. void digi() {
  35. if (op == 0) {
  36. a = atof(yytext); // Convert the first number to float
  37. } else {
  38. b = atof(yytext); // Convert the second number to float
  39. switch (op) {
  40. case 1: a = a + b; break; // Addition
  41. case 2: a = a - b; break; // Subtraction
  42. case 3: a = a * b; break; // Multiplication
  43. case 4:
  44. if (b == 0) {
  45. printf("Error: Division by zero\n");
  46. exit(1); // Exit on division by zero
  47. }
  48. a = a / b; break; // Division
  49. case 5: a = pow(a, b); break; // Exponentiation
  50. }
  51. op = 0; // Reset the operation after executing
  52. }
  53. }
  54.  
  55. int main(int argc, char *argv[]) {
  56. yylex(); // Call Lex to start scanning
  57. return 0;
  58. }
  59.  
  60. int yywrap() {
  61. return 1; // Indicates end of input for Lex
  62. }
  63.  
Success #stdin #stdout #stderr 0.03s 6944KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/Q1SVui/prog:62:1: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit