Compiler Lab Assignment-2
Compiler Lab Assignment-2
CODE:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
vector<string> keywords = {"int", "float", "double", "char", "if", "else", "for", "while", "do",
"switch", "case", "break", "continue", "return"};
ifstream inputFile(filename);
string line;
int identifierCount = 0;
int keywordCount = 0;
int numberCount = 0;
int literalCount = 0;
string token;
if (isalnum(c) || c == '_') {
token += c;
} else {
if (!token.empty()) {
if (isKeyword(token)) {
cout << "Keyword: " << token << endl;
keywordCount++;
} else if (isdigit(token[0])) {
numberCount++;
} else {
identifierCount++;
token.clear();
if (c == '"' || c == '\'') {
if (endQuotePos != string::npos) {
cout << "Literal: " << line.substr(line.find(c), endQuotePos - line.find(c) + 1) << endl;
literalCount++;
if (!token.empty()) {
if (isKeyword(token)) {
keywordCount++;
} else if (isdigit(token[0])) {
numberCount++;
} else {
identifierCount++;
}
}
inputFile.close();
int main() {
countTokens(filename);
return 0;
INPUT:
int main() {
int num4 = 88;
float num2 = 3.14;
char ch = 'A';
if (num1 > 0) {
cout << "Positive number" << endl;
} else {
cout << "Non-positive number" << endl;
}
for (int i = 0; i < 10; ++i) {
cout << "Iteration " << i << endl;
}
return 0;
}
OUTPUT:
Result Explanation:
isKeyword function: This function takes a string argument and checks if it
matches any of the predefined C++ keywords stored in the keywords vector. It
returns true if the word is a keyword and false otherwise.
It identifies tokens based on whether they are keywords (using the isKeyword
function), numbers (if the first character is a digit), or identifiers.
main function: It simply calls the countTokens function with the filename
"input.txt" and then exits.
Expected results:
The program will read the content of "input.txt" and tokenize each line.
For each token, it will print its type (identifier, keyword, number, or literal)
along with the token itself.
At the end, it will print out the total counts of each token type.