fork(1) download
  1. Code:
  2. %{
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <math.h>
  6. int operation = 0;
  7. float operand1 = 0, operand2 = 0;
  8. void processOperand();
  9. %}
  10. digit [0-9]+(\.[0-9]+)?
  11. addition "+"
  12. subtraction "-"
  13. multiplication "*"
  14. division "/"
  15. power "\^"
  16. line_break \n
  17. %%
  18. {digit} { processOperand(); }
  19. {addition} { operation = 1; }
  20. {subtraction} { operation = 2; }
  21. {multiplication} { operation = 3; }
  22. {division} { operation = 4; }
  23. {power} { operation = 5; }
  24. {line_break} {
  25. printf("The Answer: %f\n", operand1);
  26. // Reset operands and operation after each calculation
  27. operand1 = 0;
  28. operand2 = 0;
  29. operation = 0;
  30. }
  31. .|\t|\r { /* Ignore invalid characters */ }
  32. %%
  33. void processOperand() {
  34. if (operation == 0) {
  35. operand1 = atof(yytext);
  36. } else {
  37. operand2 = atof(yytext);
  38. switch (operation) {
  39. case 1:
  40. operand1 += operand2;
  41. break;
  42. case 2:
  43. operand1 -= operand2;
  44. break;
  45. case 3:
  46. operand1 *= operand2;
  47. break;
  48. case 4:
  49. if (operand2 != 0) {
  50. operand1 /= operand2;
  51. } else {
  52. printf("Error: Division by zero!\n");
  53. operand1 = 0;
  54. }
  55. break;
  56. case 5:
  57. operand1 = pow(operand1, operand2);
  58. break;
  59. default:
  60. printf("Invalid operation.\n");
  61. }
  62. operation = 0;
  63. }
  64. }
  65. int main() {
  66. yylex();
  67. return 0;
  68. }
  69. int yywrap() {
  70. return 1;
  71. }
Success #stdin #stdout #stderr 0.03s 6840KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/cj5WvF/prog:71:0: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit