fork download
  1. /* Lex code to count and list total number of tokens */
  2.  
  3. %{
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. int n = 0; // Counter for total tokens
  8. char* tokens[1000]; // Array to store tokens (up to 1000 tokens)
  9. int tokenIndex = 0; // Index to store tokens
  10. %}
  11.  
  12. /* Rule Section */
  13. %%
  14.  
  15. "while"|"if"|"else" {
  16. n++;
  17. printf("\tkeyword: %s\n", yytext);
  18. tokens[tokenIndex++] = yytext; // Store the token
  19. }
  20.  
  21. "int"|"float" {
  22. n++;
  23. printf("\tkeyword: %s\n", yytext);
  24. tokens[tokenIndex++] = yytext; // Store the token
  25. }
  26.  
  27. [a-zA-Z_][a-zA-Z0-9_]* {
  28. n++;
  29. printf("\tidentifier: %s\n", yytext);
  30. tokens[tokenIndex++] = yytext; // Store the token
  31. }
  32.  
  33. "<="|"=="|"="|"++"|"-"|"*"|"+" {
  34. n++;
  35. printf("\toperator: %s\n", yytext);
  36. tokens[tokenIndex++] = yytext; // Store the token
  37. }
  38.  
  39. [(){}|,;] {
  40. n++;
  41. printf("\tseparator: %s\n", yytext);
  42. tokens[tokenIndex++] = yytext; // Store the token
  43. }
  44.  
  45. [0-9]*"."[0-9]+ {
  46. n++;
  47. printf("\tfloat: %s\n", yytext);
  48. tokens[tokenIndex++] = yytext; // Store the token
  49. }
  50.  
  51. [0-9]+ {
  52. n++;
  53. printf("\tinteger: %s\n", yytext);
  54. tokens[tokenIndex++] = yytext; // Store the token
  55. }
  56.  
  57. . ; // Ignore unrecognized characters
  58.  
  59. %%
  60.  
  61. /* Main function */
  62. int main() {
  63. yylex(); // Start lexical analysis
  64.  
  65. printf("\nTotal number of tokens = %d\n", n); // Print total token count
  66.  
  67. // Print the list of tokens
  68. printf("\nList of tokens:\n");
  69. for (int i = 0; i < tokenIndex; i++) {
  70. printf("%s\n", tokens[i]); // Print each token
  71. }
  72.  
  73. return 0;
  74. }
  75.  
Success #stdin #stdout #stderr 0.04s 6952KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/f0aVhO/prog:4:1: Syntax error: Operator expected
ERROR: /home/f0aVhO/prog:74:1: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit