Modern translation systems often use lexical analysis to divide an input into me
ID: 3587713 • Letter: M
Question
Modern translation systems often use lexical analysis to divide an input into meaningful units. Oncethesemeaningfulunits(orlexemesortokens)havebeenderived, othercomponentswithin the translation system are used to determine the relationships among the lexemes. Lexical analyzers (or lexers) are commonly used in compilers, interpreters, and other translation systems that you have often used. The act of lexical analysis is also known as scanning. For this assignment you are to build a lexer that will successfully scan through a set of programs expressed in the CCX programming language. You have never used CCX, and that is just ne: scanning through CCX programs won’t require intimate knowledge of CCX. Your lexer shall be written in the C programming language. You may not use C++. Your lexer will be compiled and tested using gcc on the wormulon server, so you should at least test your lexerinthissameenvironment. Youareexpresslyforbiddenfromusinganystandardtemplate library (STL) containers (e.g. ), algorithms (via ), or other facilities in your lexer. You may not use any lexer generators or other automated tools to complete this assignment.
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int checkIfKeyword(char data[]){
char lexical_keywords[32][10] = {"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"};
int i, curr_flag = 0;
for(i = 0; i < 32; ++i){
if(strcmp(lexical_keywords[i], data) == 0){
curr_flag = 1;
break;
}
}
return curr_flag;
}
int main(){
// declaring variables
char currChar, data[15], operators[] = "+-*/%=";
FILE *filePointer;
int i,j=0;
// opening file
filePointer = fopen("input.txt","r");
if(filePointer == NULL){
printf("error in file opening ");
exit(0);
}
// processing each char in file opened
while((currChar = fgetc(filePointer)) != EOF){
for(i = 0; i < 6; ++i){
if(currChar == operators[i])
printf("%c is a operator ", currChar);
}
if(isalnum(currChar)){
data[j++] = currChar;
}
else if((currChar == ' ' || currChar == ' ') && (j != 0)){
data[j] = '';
j = 0;
if(checkIfKeyword(data) == 1)
printf("%s is a keyword ", data);
else
printf("%s is a identifier ", data);
}
}
fclose(filePointer);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.