fork download
  1. %{
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. int keywords = 0, identifiers = 0, operators = 0, separators = 0;
  6.  
  7. char *keywordList[] = {
  8. "int", "float", "char", "if", "else", "return", "while", "for", "do", "switch"
  9. };
  10.  
  11. int isKeyword(char *str) {
  12. for (int i = 0; i < sizeof(keywordList)/sizeof(char*); i++) {
  13. if (strcmp(str, keywordList[i]) == 0)
  14. return 1;
  15. }
  16. return 0;
  17. }
  18. %}
  19.  
  20. %option noyywrap
  21.  
  22. %%
  23. [a-zA-Z_][a-zA-Z0-9_]* {
  24. if (isKeyword(yytext)) {
  25. keywords++;
  26. printf("Keyword: %s\n", yytext);
  27. } else {
  28. identifiers++;
  29. printf("Identifier: %s\n", yytext);
  30. }
  31. }
  32.  
  33. "=="|"!="|"<="|">="|"="|"+"|"-"|"*"|"/"|"<"|">" {
  34. operators++;
  35. printf("Operator: %s\n", yytext);
  36. }
  37.  
  38. [(){},;:\[\]] {
  39. separators++;
  40. printf("Separator: %s\n", yytext);
  41. }
  42.  
  43. [0-9]+ ; // Ignore numbers
  44. [ \t\n]+ ; // Ignore whitespace
  45. . ; // Ignore other characters
  46. %%
  47.  
  48. int main() {
  49. char str[1000];
  50. printf("Enter code:\n");
  51. fgets(str, sizeof(str), stdin);
  52. YY_BUFFER_STATE buffer = yy_scan_string(str);
  53. yylex();
  54. yy_delete_buffer(buffer);
  55.  
  56. printf("\nToken Counts:\n");
  57. printf("Keywords: %d\n", keywords);
  58. printf("Identifiers: %d\n", identifiers);
  59. printf("Operators: %d\n", operators);
  60. printf("Separators: %d\n", separators);
  61.  
  62. return 0;
  63. }
  64.  
  65. int yywrap() {
  66. return 1;
  67. }
  68.  
Success #stdin #stdout #stderr 0.02s 6976KB
stdin
Utkarsha
stdout
Standard output is empty
stderr
ERROR: /home/xBIqOV/prog:2:1: Syntax error: Operator expected
ERROR: /home/xBIqOV/prog:67:1: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit