我在大学学习编译器设计,该程序用于识别每个单词
,数字
,操作
,分隔符
在用户输入的行中
就像当您输入 int i = 0 ;
(每个单词之间需要空格)
它将int
标识为关键字,i
标识为id,=
标识为相等,0
标识为数字,;
作为输出中的分隔符
我的老师给了我一个任务,将本节中的“if else
”更改为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++;
}
}
所以我尝试了大约一周的时间来解决这个问题,但没有成功。 我被困在这里,有人可以帮助我吗,谢谢。
这是代码的其余部分
#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; }```
最佳答案
自 switch only works for integral types您可能想使用 std::map将字符串链接到整数类型。
最小工作示例:
#include <iostream>
#include <map>
#include <string>
int main()
{
int num_token=0;
std::string token[4]{"int","="};
std::map<std::string,int> m{{"int",0},{"string",0},{"float",0},{"=",1}};
for(int j=0;j<2;j++){
switch(m[token[j]]){
case(0):
std::cout<<"keyword : "<<token[j]<<std::endl;
num_token++;
break;
case(1):
std::cout<<"eq : "<<token[j]<<std::endl;
num_token++;
break;
}
}
return 0;
}
关于c++ - 使用 switch case 代替 if else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62554135/