I study Compiler Design in my university this program is used to identify every word
,number
,operation
,separator
in an entered line by the user
like when you enter int i = 0 ;
(spaces between every word are necessary)
it identifies int
as keyword, i
as id, =
as equal, 0
as number and ;
as separator in the output
and my instructor gave me a task to change the "if else
" in this section to switch
for(int j=0;j<=k;j++){
if(token[j]=="int"|| token[j]=="string"||token[j]=="float")
{
cout<<"keyword : "<<token[j]<<endl;
num_token++;
}
else if(token[j]=="*"||token[j]=="+"||token[j]=="-"||token[j]=="/")
{
cout<<"operation : "<<token[j]<<endl;
num_token++;
}
else if(token[j]==","||token[j]==";")
{
cout<<"separator : "<<token[j]<<endl;
num_token++;
}
else if(token[j]=="=")
{
cout<<"equal : "<<token[j]<<endl;
num_token++;
}
else if(token[j]>="0"&&token[j]<="9")
{
cout<<"Number : "<<token[j]<<endl;
num_token++;
}
else if(token[j]>="a"&&token[j]<="z")
{
cout<<"ID : "<<token[j]<<endl;
num_token++;
}
}
so I was trying for about a week to figure something out myself for this problem but to no avail. I'm stuck here can someone help me please, thank you.
This is the rest of the code
#include<iostream>
using namespace std;
int main(){
int num;
string st,st1;
string token[30];
int k=0;
int num_token=0;
cout<<"Enter How Many Lines : "<<endl;
cin>>num;
cout<<"Please Enter The Line You Want To Process : "<<endl;
for(int ii=0;ii<=num;ii++){
getline(cin,st);
for(int i=0;st[i]!='\0';i++){
if(st[i]!= ' ')
st1+=st[i];
else{
token[k]=st1;
k++;
st1="";
}
}
token[k]=st1;
for(int j=0;j<=k;j++){
if(token[j]=="int"|| token[j]=="string"||token[j]=="float")
{
cout<<"keyword : "<<token[j]<<endl;
num_token++;
}
else if(token[j]=="*"||token[j]=="+"||token[j]=="-"||token[j]=="/")
{
cout<<"operation : "<<token[j]<<endl;
num_token++;
}
else if(token[j]==","||token[j]==";")
{
cout<<"separator : "<<token[j]<<endl;
num_token++;
}
else if(token[j]=="=")
{
cout<<"equal : "<<token[j]<<endl;
num_token++;
}
else if(token[j]>="0"&&token[j]<="9")
{
cout<<"Number : "<<token[j]<<endl;
num_token++;
}
else if(token[j]>="a"&&token[j]<="z")
{
cout<<"ID : "<<token[j]<<endl;
num_token++;
}
}
token[30]="";
k=0;
if(ii<num && ii>0){
cout<<" "<<endl;
cout<<"Please Enter The Line Again"<<endl;
}
}
cout<<"total Number of Tokens is : "<<num_token;
return 0; }```