fork download
  1. /* Lex program to recognize valid arithmetic expression
  2. and identify the identifiers and operators */
  3. %{
  4. #include <stdio.h>
  5. #include <string.h>
  6. int operators_count = 0, operands_count = 0, valid = 1, top = -1, l = 0, j = 0;
  7. char operands[10][10], operators[10][10], stack[100];
  8. %}
  9. %%
  10. "(" {
  11. top++;
  12. stack[top] = '(';
  13. }
  14. "{" {
  15. top++;
  16. stack[top] = '{';
  17. }
  18. "[" {
  19. top++;
  20. stack[top] = '[';
  21. }
  22. ")" {
  23. if (stack[top] != '(') {
  24. valid = 0;
  25. }
  26. else if(operands_count>0 && (operands_count-operators_count)!=1){
  27. valid=0;
  28. }
  29. else{
  30. top--;
  31. operands_count=1;
  32. operators_count=0;
  33. }
  34. }
  35. "}" {
  36. if (stack[top] != '{') {
  37. valid = 0;
  38. }
  39. else if(operands_count>0 && (operands_count-operators_count)!=1){
  40. valid=0;
  41. }
  42. else{
  43. top--;
  44. operands_count=1;
  45. operators_count=0;
  46. }
  47. }
  48. "]" {
  49. if (stack[top] != '[') {
  50. valid = 0;
  51. }
  52. else if(operands_count>0 && (operands_count-operators_count)!=1){
  53. valid=0;
  54. }
  55. else{
  56. top--;
  57. operands_count=1;
  58. operators_count=0;
  59. }
  60.  
  61. }
  62. "+"|"-"|"*"|"/" {
  63. operators_count++;
  64. strcpy(operators[l], yytext);
  65. l++;
  66. }
  67. [0-9]+|[a-zA-Z][a-zA-Z0-9_]* {
  68. operands_count++;
  69. strcpy(operands[j], yytext);
  70. j++;
  71. }
  72. %%
  73.  
  74.  
  75. int yywrap()
  76. {
  77. return 1;
  78. }
  79. int main()
  80. {
  81. int k;
  82. printf("Enter the arithmetic expression: ");
  83. yylex();
  84.  
  85. if (valid == 1 && top == -1) {
  86. printf("\nValid Expression\n");
  87. }
  88. else
  89. printf("\nInvalid Expression\n");
  90.  
  91. return 0;
  92. }
  93.  
Success #stdin #stdout #stderr 0.02s 6916KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/3XdIJ9/prog:92:1: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit