gpt4 book ai didi

c++ - 在枚举中编写代码

转载 作者:太空狗 更新时间:2023-10-29 20:44:13 25 4
gpt4 key购买 nike

我在中写了一个关于如何访问我的字段的特定方法,但我的老师告诉我我应该使用enum

如何重写此代码以使用 enum 而不是使用 goto

void SetType() {
cout << "Book SetType" << endl;
Choice: cout << "Please Select from the list: \n "
<< "1- Technical literature \n "
<< "2- Fiction literature \n "
<< "3- Textbook" << endl;
int i;
cin >> i;

switch (i) {
case 1:
Type = "Technical literature";
break;
case 2:
Type = "Fiction literature";
break;
case 3:
Type = "Textbook";
break;
default:
cout << "Erorr you entered a wrong choice" << endl;
goto Choice;
}
}

最佳答案

只需使用循环而不是 gotos 它将成为意大利面条代码。枚举很好,不关心定义的数字,因为如果您添加新的,它们会自动递增。

#include <iostream>
#include <string>
void SetType();

using namespace std;
string Type;
int main()
{
SetType();

cout << "so you choose " << Type << endl;
return 0;
}
enum select
{
Technical_literature = 1,
Fiction_literature,
Textbook
};

void SetType() {
cout<<"Book SetType"<<endl;
while(1)
{
cout<<"Please Select from the list: \n 1- Technical literature \n 2- Fiction literature \n 3- Textbook"<<endl;
int i;
cin >> i;

switch(i) {
case Technical_literature:
Type="Technical literature";
return;
case Fiction_literature:
Type="Fiction literature";
return;
case Textbook:
Type="Textbook";
return;
default:
cout << "Erorr you entered a wrong choice" << endl;

}
}
}

关于c++ - 在枚举中编写代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13479724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com