fork download
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #include <string.h>
  4.  
  5. typedef struct
  6. {
  7. char lexeme[100];
  8. char type[20];
  9. } Token;
  10.  
  11. const char* keywords[] = {"int", "float", "if", "else", "while", "return", "void", "char", "for", "double"};
  12. const int num_keywords = sizeof(keywords) / sizeof(keywords[0]);
  13.  
  14. int isKeyword(const char* token)
  15. {
  16. for (int i = 0; i < num_keywords; i++)
  17. {
  18. if (strcmp(token, keywords[i]) == 0)
  19. {
  20. return 1;
  21. }
  22. }
  23. return 0;
  24. }
  25.  
  26. Token classifyToken(const char *token)
  27. {
  28. Token t;
  29. strcpy(t.lexeme, token);
  30.  
  31. if (isKeyword(token))
  32. strcpy(t.type, "KEYWORD");
  33. else if (isdigit(token[0]))
  34. strcpy(t.type, "NUMBER");
  35. else if (isalpha(token[0]) || token[0] == '_')
  36. strcpy(t.type, "IDENTIFIER");
  37. else if (strchr("+-*/=<>!", token[0]))
  38. strcpy(t.type, "OPERATOR");
  39. else if (strchr(";(),{}", token[0]))
  40. strcpy(t.type, "DELIMITER");
  41. else
  42. strcpy(t.type, "UNKNOWN");
  43.  
  44. return t;
  45. }
  46.  
  47. void lexicalAnalyzer(const char *input)
  48. {
  49. char token[100];
  50. int index = 0;
  51.  
  52. for (int i = 0; i < strlen(input); i++)
  53. {
  54. char ch = input[i];
  55.  
  56. if (isspace(ch))
  57. {
  58. if (index > 0)
  59. {
  60. token[index] = '\0';
  61. Token t = classifyToken(token);
  62. printf("%s: %s\n", t.type, t.lexeme);
  63. index = 0;
  64. }
  65. }
  66. else if (strchr("+-*/=<>!", ch) || strchr(";(),{}", ch))
  67. {
  68. if (index > 0)
  69. {
  70. token[index] = '\0';
  71. Token t = classifyToken(token);
  72. printf("%s: %s\n", t.type, t.lexeme);
  73. index = 0;
  74. }
  75.  
  76. char next = input[i + 1];
  77.  
  78. if (strchr("+-*/=<>!", ch) && next == '=')
  79. {
  80. token[0] = ch;
  81. token[1] = '=';
  82. token[2] = '\0';
  83. Token t = classifyToken(token);
  84. printf("%s: %s\n", t.type, t.lexeme);
  85. i++;
  86. }
  87. else
  88. {
  89. token[0] = ch;
  90. token[1] = '\0';
  91. Token t = classifyToken(token);
  92. printf("%s: %s\n", t.type, t.lexeme);
  93. }
  94. }
  95. else
  96. {
  97. token[index++] = ch;
  98. }
  99. }
  100.  
  101. if (index > 0)
  102. {
  103. token[index] = '\0';
  104. Token t = classifyToken(token);
  105. printf("%s: %s\n", t.type, t.lexeme);
  106. }
  107. }
  108.  
  109. int main()
  110. {
  111. printf("Enter a simple C code snippet: ");
  112. char input[100] = "+= -= *= /= <= >= != ==";
  113.  
  114.  
  115. printf("\nTokens Found:\n");
  116. lexicalAnalyzer(input);
  117.  
  118. return 0;
  119. }
  120.  
Success #stdin #stdout 0s 5328KB
stdin
Standard input is empty
stdout
Enter a simple C code snippet: 
Tokens Found:
OPERATOR: +=
OPERATOR: -=
OPERATOR: *=
OPERATOR: /=
OPERATOR: <=
OPERATOR: >=
OPERATOR: !=
OPERATOR: ==