fork download
  1. %{
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. #define MAX 1000
  7.  
  8. char identifiers[MAX][50];
  9. int id_count = 0;
  10.  
  11. char operators[MAX][5];
  12. int op_count = 0;
  13.  
  14. // Function to check if identifier/operator already stored
  15. int is_present(char arr[][50], int count, char* token) {
  16. for (int i=0; i<count; i++) {
  17. if (strcmp(arr[i], token) == 0)
  18. return 1;
  19. }
  20. return 0;
  21. }
  22. %}
  23.  
  24. %%
  25.  
  26. [ \t\n]+ ; // ignore whitespace
  27.  
  28. [a-zA-Z_][a-zA-Z0-9_]* {
  29. if (!is_present(identifiers, id_count, yytext)) {
  30. strcpy(identifiers[id_count++], yytext);
  31. }
  32. }
  33.  
  34. [+\-*/=()] {
  35. if (!is_present(operators, op_count, yytext)) {
  36. strcpy(operators[op_count++], yytext);
  37. }
  38. }
  39.  
  40. [0-9]+(\.[0-9]+)? ; // ignore numbers
  41.  
  42. . { printf("Invalid character: %s\n", yytext); exit(1); }
  43.  
  44. %%
  45.  
  46. int main() {
  47. printf("Enter an arithmetic expression:\n");
  48. yylex();
  49.  
  50. printf("\nIdentifiers found:\n");
  51. for (int i=0; i<id_count; i++) {
  52. printf("%s\n", identifiers[i]);
  53. }
  54.  
  55. printf("\nOperators found:\n");
  56. for (int i=0; i<op_count; i++) {
  57. printf("%s\n", operators[i]);
  58. }
  59.  
  60. return 0;
  61. }
  62.  
Success #stdin #stdout #stderr 0.02s 7024KB
stdin
a = b + 5 * c
stdout
Standard output is empty
stderr
ERROR: /home/jhOwYs/prog:2:1: Syntax error: Operator expected
ERROR: /home/jhOwYs/prog:61:1: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit