Program to implement lexical analyzer in c++.
Program:
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
main()
{
int i,j,k,f,len,t;
char exp[100],word[12][12];
char op[10]={'+','*','-','/'};
char key[10][10]={"while","do","else","if"};
cout<<"Enter the expression\n";
cin>>exp;
len=strlen(exp);t=0;
for(i=0;i<len;i++)
{
j=0;f=0;
if(isalpha(exp[i]))
{
while(isalpha(exp[i])||isdigit(exp[i]))
{
word[t][j]=exp[i];
i++;j++;
}
word[t][j]='\0';
i--;
for(k=0;k<10;k++)
{
if(word[t]==key[k])
{
cout<<"The "<<word[t]<<" is keyword\n";
f=1;
break;
}
}
if(f==0)
{
cout<<"The "<<word[t]<<" is identifier\n";
}
}
else if(isdigit(exp[i]))
{
while(isdigit(exp[i]))
{
word[t][j]=exp[i];
i++;j++;
}
i--;
cout<<"The "<<word[t]<<" is constant\n";
}
else
{
cout<<"The "<<exp[i]<<" is operator\n";
}
t++;
}
getch();
}
Program:
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
main()
{
int i,j,k,f,len,t;
char exp[100],word[12][12];
char op[10]={'+','*','-','/'};
char key[10][10]={"while","do","else","if"};
cout<<"Enter the expression\n";
cin>>exp;
len=strlen(exp);t=0;
for(i=0;i<len;i++)
{
j=0;f=0;
if(isalpha(exp[i]))
{
while(isalpha(exp[i])||isdigit(exp[i]))
{
word[t][j]=exp[i];
i++;j++;
}
word[t][j]='\0';
i--;
for(k=0;k<10;k++)
{
if(word[t]==key[k])
{
cout<<"The "<<word[t]<<" is keyword\n";
f=1;
break;
}
}
if(f==0)
{
cout<<"The "<<word[t]<<" is identifier\n";
}
}
else if(isdigit(exp[i]))
{
while(isdigit(exp[i]))
{
word[t][j]=exp[i];
i++;j++;
}
i--;
cout<<"The "<<word[t]<<" is constant\n";
}
else
{
cout<<"The "<<exp[i]<<" is operator\n";
}
t++;
}
getch();
}
Output:
0 comments:
Post a Comment