fork download
  1. %{
  2. #include <stdio.h>
  3.  
  4. int word_count = 0;
  5.  
  6. // Helper function to check if a string is a valid C++ identifier or word
  7. int is_word(const char *s) {
  8. while (*s) {
  9. if (isalnum(*s) || *s == '_')
  10. return 1;
  11. s++;
  12. }
  13. return 0;
  14. }
  15. %}
  16.  
  17. %%
  18.  
  19. // Skip single-line comments
  20. "//".* { /* Ignore */ }
  21.  
  22. // Skip multi-line comments
  23. "/*"([^*]|\*+[^*/])*\*+"/" { /* Ignore */ }
  24.  
  25. // Skip string literals
  26. \"([^\\\"]|\\.)*\" { /* Ignore */ }
  27.  
  28. // Match words (identifiers, keywords, etc.)
  29. [a-zA-Z_][a-zA-Z0-9_]* { word_count++; }
  30.  
  31. // Match numbers (considered as words)
  32. [0-9]+ { word_count++; }
  33.  
  34. // Skip whitespace
  35. [ \t\n\r]+ { /* Ignore */ }
  36.  
  37. // Everything else
  38. . { /* Ignore punctuation, etc. */ }
  39.  
  40. %%
  41.  
  42. int main(int argc, char **argv)
  43. {
  44. if (argc > 1) {
  45. FILE *file = fopen(argv[1], "r");
  46. if (!file) {
  47. perror("Cannot open file");
  48. return 1;
  49. }
  50. yyin = file;
  51. }
  52.  
  53. yylex();
  54.  
  55. printf("Total number of words: %d\n", word_count);
  56. return 0;
  57. }
  58.  
  59. int yywrap() {
  60. return 1;
  61. }
  62.  
Success #stdin #stdout #stderr 0.04s 6864KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/qEt5Lt/prog:61:1: Syntax error: end_of_file_in_quasi_quotation
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit