fork download
  1. %option noyywrap
  2.  
  3. %{
  4. #include<stdio.h>
  5. #include<stdlib.h>
  6.  
  7. int num1 = 0, num2 = 0;
  8. char op;
  9. %}
  10.  
  11. %%
  12. [0-9]+ {
  13. if(num1 == 0)
  14. num1 = atoi(yytext);
  15. else
  16. num2 = atoi(yytext);
  17. }
  18.  
  19. [\+\-\*/] {
  20. op = yytext[0];
  21. }
  22.  
  23. \n {
  24. switch(op)
  25. {
  26. case '+':
  27. printf("Result = %d\n", num1 + num2);
  28. break;
  29.  
  30. case '-':
  31. printf("Result = %d\n", num1 - num2);
  32. break;
  33.  
  34. case '*':
  35. printf("Result = %d\n", num1 * num2);
  36. break;
  37.  
  38. case '/':
  39. if(num2 == 0)
  40. printf("Division by zero error\n");
  41. else
  42. printf("Result = %d\n", num1 / num2);
  43. break;
  44.  
  45. default:
  46. printf("Invalid operator\n");
  47. }
  48.  
  49. num1 = num2 = 0;
  50. }
  51.  
  52. [ \t] ;
  53.  
  54. . {
  55. printf("Invalid character\n");
  56. }
  57. %%
  58.  
  59. int main()
  60. {
  61. printf("Enter expression (Example: 10+20):\n");
  62. yylex();
  63. return 0;
  64. }
Success #stdin #stdout #stderr 0.02s 6828KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/hK2UHz/prog:4:1: Syntax error: Operator expected
ERROR: /home/hK2UHz/prog:64:0: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit