在枚举中编写代码

时间:2012-11-20 18:28:02

标签: c++

我写了一个关于如何在class中访问我的字段的方法,但我的老师告诉我应该使用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;
    }
}

2 个答案:

答案 0 :(得分:4)

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

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

        }
    }
}

答案 1 :(得分:1)

你的老师意味着你不需要在整个地方硬编码常量,而是要将你的i声明为枚举。

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

some_type i;

然后阅读枚举。