#include <stdio.h> #include <ctype.h> #include <string.h> #include <stdbool.h> bool is_identifier(const char *token) { if (!isalpha(token[0]) && token[0] != '_') return false; for (int i = 1; token[i] != '\0'; i++) { if (!isalnum(token[i]) && token[i] != '_') return false; } return true; } bool is_constant(const char *token) { int i = 0, dot_count = 0; if (token[i] == '-' || token[i] == '+') i++; if (token[i] == '\0') return false; for (; token[i] != '\0'; i++) { if (token[i] == '.') { if (++dot_count > 1) return false; } else if (!isdigit(token[i])) { return false; } } return true; } bool is_operator(const char *token) { const char operators[] = {"+", "-", "", "/", "=", "==", "!=", "<", ">", "<=", ">="}; for (int i = 0; i < sizeof(operators) / sizeof(operators[0]); i++) { if (strcmp(token, operators[i]) == 0) return true; } return false; } int main() { char token[100]; printf("Enter a token: "); scanf("%s", token); if (is_operator(token)) printf("Operator\n"); else if (is_constant(token)) printf("Constant\n"); else if (is_identifier(token)) printf("Identifier\n"); else printf("Unknown\n"); return 0; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter