Writing a Lexical Analyzer in C++ is a good step toward building a compiler or interpreter. A lexical analyzer (or lexer) breaks up a source code file into tokens such as keywords, identifiers, literals, operators, etc.
Below is a simple Lexical Analyzer example in C++ that handles:
Keywords: int, float, return, etc.
Identifiers
Numbers (integers)
Operators: +, -, *, /, =
Delimiters: ;, (, ), {, }
✅ C++ Lexical Analyzer Source Code:
cpp
#include <iostream>
#include <fstream>
#include <cctype>
#include <unordered_set>
#include <string>
using namespace std;
// Set of C keywords
unordered_set<string> keywords = {
"auto", "break", "case", "char", "const", "continue", "default",
"do", "double", "else", "enum", "extern", "float", "for", "goto",
"if", "int", "long", "register", "return", "short", "signed",
"sizeof", "static", "struct", "switch", "typedef", "union",
"unsigned", "void", "volatile", "while"
};
// Helper function to check if a character is a delimiter
bool isDelimiter(char ch) {
return ch == ' ' || ch == ',' || ch == ';' || ch == '(' || ch == ')' ||
ch == '{' || ch == '}' || ch == '\n' || ch == '\t';
}
// Helper function to check if a character is an operator
bool isOperator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '=' || ch == '<' || ch == '>';
}
// Helper function to check if a string is a keyword
bool isKeyword(const string &str) {
return keywords.find(str) != keywords.end();
}
// Helper function to check if a string is a valid identifier
bool isIdentifier(const string &str) {
if (str.empty() || isdigit(str[0]))
return false;
for (char ch : str) {
if (!isalnum(ch) && ch != '_')
return false;
}
return true;
}
// Helper function to check if a string is a number
bool isNumber(const string &str) {
for (char ch : str) {
if (!isdigit(ch))
return false;
}
return true;
}
// Main lexer function
void lexicalAnalyzer(const string &filename) {
ifstream file(filename);
if (!file.is_open()) {
cerr << "Error opening file: " << filename << endl;
return;
}
char ch;
string buffer;
while (file.get(ch)) {
if (isDelimiter(ch)) {
if (!buffer.empty()) {
if (isKeyword(buffer))
cout << buffer << " : Keyword" << endl;
else if (isNumber(buffer))
cout << buffer << " : Number" << endl;
else if (isIdentifier(buffer))
cout << buffer << " : Identifier" << endl;
else
cout << buffer << " : Invalid Identifier" << endl;
buffer.clear();
}
if (ch != ' ' && ch != '\n' && ch != '\t')
cout << ch << " : Delimiter" << endl;
} else if (isOperator(ch)) {
if (!buffer.empty()) {
if (isKeyword(buffer))
cout << buffer << " : Keyword" << endl;
else if (isNumber(buffer))
cout << buffer << " : Number" << endl;
else if (isIdentifier(buffer))
cout << buffer << " : Identifier" << endl;
else
cout << buffer << " : Invalid Identifier" << endl;
buffer.clear();
}
cout << ch << " : Operator" << endl;
} else {
buffer += ch;
}
}
// For any remaining buffer content at EOF
if (!buffer.empty()) {
if (isKeyword(buffer))
cout << buffer << " : Keyword" << endl;
else if (isNumber(buffer))
cout << buffer << " : Number" << endl;
else if (isIdentifier(buffer))
cout << buffer << " : Identifier" << endl;
else
cout << buffer << " : Invalid Identifier" << endl;
}
file.close();
}
int main() {
string filename;
cout << "Enter the source code filename (e.g., input.c): ";
cin >> filename;
lexicalAnalyzer(filename);
return 0;
}
📁 Example Input (input.c):
Create a file named input.c in the same directory:
c
int main() {
int a = 10;
float b = 25.5;
a = a + 5;
return 0;
}
📤 Output:
code
int : Keyword
main : Identifier
( : Delimiter
) : Delimiter
{ : Delimiter
int : Keyword
a : Identifier
= : Operator
10 : Number
; : Delimiter
float : Keyword
b : Identifier
= : Operator
25 : Number
. : Delimiter
5 : Number
; : Delimiter
a : Identifier
= : Operator
a : Identifier
+ : Operator
5 : Number
; : Delimiter
return : Keyword
0 : Number
; : Delimiter
} : Delimiter
🛠️ How to Compile and Run:
bash
g++ -o lexer lexer.cpp
./lexer
📝 Notes:
You can extend this lexer to handle floating point numbers, strings, comments, etc.
For a more robust lexer, consider using tools like Flex.
Let me know if you'd like a version that includes floating-point numbers, string literals, or multi-character operators (==, <=, etc.).