fork download
  1. %{
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. int intCount = 0;
  6. int doubleCount = 0;
  7. int identifierCount = 0;
  8. int stringCount = 0;
  9. int longestStringLength = 0;
  10. int nonWordCharCount = 0;
  11. int lineCount = 0;
  12. %}
  13.  
  14. %3
  15.  
  16. /* regular definitions */
  17. delim [ \t\n]
  18. ws {delim}+
  19.  
  20. letter [A-Za-z]
  21. digit [0-9]
  22. identifier ({letter}|{digit})*
  23. type (double|lint|char|signed|float|short|void)
  24. keyword (type|main|auto|struct|break|else|long|switch|case|enum|register|typedef|extern|return|union|continue|for|void|do|if|static|while|default|goto|sizeof|volatile|const|printf)
  25.  
  26. %%
  27.  
  28. {ws} ; /* skip whitespace */
  29.  
  30. int {printf("int\n"); intCount++;}
  31. double {printf("double\n"); doubleCount++;}
  32.  
  33. {identifier} {
  34. printf("%s\n", yytext);
  35. identifierCount++;
  36. }
  37.  
  38. \"([^\"\\n]|(\\\.))*\" {
  39. printf("String\n");
  40. stringCount++;
  41. int len = strlen(yytext) - 2; // Exclude the surrounding double quotes
  42. if (len > longestStringLength) {
  43. longestStringLength = len;
  44. }
  45. }
  46.  
  47. \'[^\'\\n]\'. /* ignore single-quoted strings */
  48.  
  49. [+-]?{digit}+(\.{digit}+)? { /* recognize numbers */
  50. if (strchr(yytext, '.') != NULL) {
  51. printf("double\n");
  52. doubleCount++;
  53. } else {
  54. printf("int\n");
  55. intCount++;
  56. }
  57. }
  58.  
  59. . {nonWordCharCount++;}
  60.  
  61. \n {lineCount++;}
  62.  
  63. %%
  64.  
  65. int main(int argc, char *argv[]) {
  66. if (argc != 2) {
  67. printf("Usage: %s <input_file>\n", argv[0]);
  68. return 1;
  69. }
  70.  
  71. FILE *inputFile = fopen(argv[1], "r");
  72. if (inputFile == NULL) {
  73. perror("Unable to open input file");
  74. return 1;
  75. }
  76.  
  77. yyin = inputFile;
  78. yylex();
  79.  
  80. fclose(inputFile);
  81.  
  82. printf("The number of integer numbers is %d\n", intCount);
  83. printf("The number of double numbers is %d\n", doubleCount);
  84. printf("The number of Identifiers is %d\n", identifierCount);
  85. printf("The number of String is %d\n", stringCount);
  86. printf("The longest String is \"%s\" of length %d\n", yytext, longestStringLength);
  87. printf("The number of characters that are not word characters: %d\n", nonWordCharCount);
  88. printf("The number of lines: %d\n", lineCount);
  89.  
  90. return 0;
  91. }
  92.  
Success #stdin #stdout #stderr 0.02s 6880KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/h26uvU/prog:91:1: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit