3

我写了一个关于如何访问我的字段的方法class,但是我的老师告诉我应该使用enum.

如何重新编写此代码以使用enum而不使用gotos?

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;
    }
}
4

2 回答 2

4

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

#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;

        }
    }
}
于 2012-11-20T18:46:29.233 回答
1

您的老师的意思是,您需要将 i 声明为枚举,而不是到处硬编码常量。

enum some_type {
    type_techlit=1, type_fiction, type_textbook
};

some_type i;

然后阅读枚举。

于 2012-11-20T18:31:51.630 回答