Reputation: 11
this is lexical analyzer code in c++ can any one explain me that code and also tell me how to read string from a file
using namespace std;
function
int isKeyword(char buffer[]){
char 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, flag = 0;
what is happening here? why we use strcmp and what its used for
for(i = 0; i < 32; ++i){
if(strcmp(keywords[i], buffer) == 0){
flag = 1;
break;
}
}
return flag;
}
main
int main()
{
char ch, buffer[15];
ifstream fin("program.txt");
int j=0;
if(!fin.is_open()){
cout<<"error while opening the file\n";
exit(0);
}
while(!fin.eof()){
ch = fin.get();
what is happening here?
if(isalnum(ch))
{
buffer[j++] = ch;
}
else if((ch == ' ' || ch == '\n') && (j != 0)){
buffer[j] = '\0';
j = 0;
if(isKeyword(buffer) == 1)
cout<<buffer<<" is keyword\n";
else
cout<<buffer<<" is identifier\n";
}
}
fin.close();
return 0;
}
Upvotes: 1
Views: 124
Reputation: 119
overall idea is to have a data structure keywords[n][m]
hold all the keywords and then read a file word by word and check whether the word is in the keywords[n][m]
array or not i.e. whether it is a keyword OR not.
In the main function, a file is opened and is read word by word till end and the word is passed to function iskeyword()
to decide whether the word is keyword or not. Inside the iskeyword()
function, we iterate through the 2-d array keywords[n][m]
in a for loop and use the strcmp function to check whether the word string passed as input argument is same as an element of the 2-d array or not. If the word is in 2-d array then its a keyword and the function returns 1 and is keyword
is printed on screen. Otherwise '0' is returned and 'is identifier' is output to screen.
more about strcmp here
hope this helps!
Upvotes: 1