| #include <iomanip>
|
| #include <iostream>
|
| #include <fstream>
|
| #include <string>
|
| #include <vector>
|
| #include <unordered_set>
|
| #include <cctype>
|
|
|
| using namespace std;
|
|
|
| // (The same declarations for keywords, operators, delimiters, and utility functions)
|
|
|
| // Classify the tokens and display them in a tabulated format
|
| void classifyTokens(const vector<string>& tokens) {
|
| // Print table header
|
| cout << left << setw(20) << "Token"
|
| << setw(20) << "Type" << endl;
|
| cout << string(40, '-') << endl;
|
|
|
| for (const string& token : tokens) {
|
| string type;
|
| if (isKeyword(token)) {
|
| type = "Keyword";
|
| } else if (isOperator(token)) {
|
| type = "Operator";
|
| } else if (isNumber(token)) {
|
| type = "Number";
|
| } else if (token.size() >= 2 && token[0] == '"' && token.back() == '"') {
|
| type = "String Literal";
|
| } else if (token.size() >= 2 && token[0] == '\'' && token.back() == '\'') {
|
| type = "Character Literal";
|
| } else if (isDelimiter(token[0])) {
|
| type = "Delimiter";
|
| } else if (token[0] == '_' || isalpha(token[0])) {
|
| type = "Identifier";
|
| } else {
|
| type = "Unrecognized";
|
| }
|
|
|
| // Print token and its type
|
| cout << left << setw(20) << token
|
| << setw(20) << type << endl;
|
| }
|
| }
|
|
|
| int main() {
|
| string filePath;
|
| cout << "Enter the path to the C source file: ";
|
| getline(cin, filePath);
|
|
|
| ifstream file(filePath);
|
| if (!file.is_open()) {
|
| cerr << "Error: Could not open file at " << filePath << endl;
|
| return 1;
|
| }
|
|
|
| string code((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
|
| file.close();
|
|
|
| // Remove comments from the code
|
| string cleanedCode = removeComments(code);
|
|
|
| // Tokenize the cleaned code
|
| vector<string> tokens = tokenize(cleanedCode);
|
|
|
| // Classify and display tokens in tabulated format
|
| cout << "\nIdentified Tokens:\n";
|
| classifyTokens(tokens);
|
|
|
| return 0;
|
| }
|