fork download
  1.  
  2. %{
  3. #include <stdio.h>
  4. int comment_lines = 0; // Count of comment lines (single-line and multi-line)
  5. int identifiers = 0; // Count of identifiers
  6. int characters = 0; // Count of characters
  7. int words = 0; // Count of words
  8. %}
  9.  
  10. /* Definitions */
  11. DIGIT [0-9]
  12. LETTER [a-zA-Z_]
  13. IDENTIFIER {LETTER}({LETTER}|{DIGIT})*
  14. WORD [a-zA-Z]+
  15.  
  16. /* Rules */
  17. %%
  18.  
  19. "//"[^\n]*\n { comment_lines++; characters += yyleng; } /* Single-line comment */
  20. "/*"([^*]|\*+[^*/])*\*+"/" { comment_lines++; characters += yyleng;
  21. /* Count multi-line comments; increment for each line if spans multiple */
  22. for(int i = 0; i < yyleng; i++) if(yytext[i] == '\n') comment_lines++; }
  23.  
  24. {IDENTIFIER} { identifiers++; characters += yyleng; words++; } /* Identifiers are also words */
  25. {WORD} { words++; characters += yyleng; } /* Other words */
  26. [ \t\n] { characters += yyleng; } /* Whitespace characters */
  27. . { characters++; } /* Any other character */
  28.  
  29. %%
  30.  
  31. /* User Code */
  32. int main(int argc, char* argv[]) {
  33. if(argc > 1) { // If a file is provided as argument
  34. yyin = fopen(argv[1], "r");
  35. if(!yyin) {
  36. perror("Error opening file");
  37. return 1;
  38. }
  39. } else { // Use standard input
  40. yyin = stdin;
  41. printf("Enter the input (Ctrl+D to end):\n");
  42. }
  43.  
  44. yylex(); // Run the lexical analyzer
  45.  
  46. printf("Number of comment lines: %d\n", comment_lines);
  47. printf("Number of identifiers: %d\n", identifiers);
  48. printf("Number of characters: %d\n", characters);
  49. printf("Number of words: %d\n", words);
  50.  
  51. if(argc > 1) fclose(yyin);
  52. return 0;
  53. }
  54.  
  55. int yywrap() {
  56. return 1; // Indicate end of input
  57. }
Success #stdin #stdout #stderr 0.03s 6936KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/tHc4Fq/prog:3:1: Syntax error: Operator expected
ERROR: /home/tHc4Fq/prog:57:0: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit