3

のフィールドにアクセスする方法について特定のメソッドを作成しましたclassが、先生から、を使用するように言われましたenum

enumsを使用せずに使用するようにこのコードを書き直すにはどうすればよい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;
    }
}
4

2 に答える 2

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;

        }
    }
}
于 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 に答える