kryticrecte
kryticrecte

Reputation: 377

writing code in enum

I wrote a certain method on how to access my fields in a class, but my teacher told me I should use an enum.

How can I re-write this code to use an enum and not use 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;
    }
}

Upvotes: 3

Views: 154

Answers (2)

phschoen
phschoen

Reputation: 2081

just use loops instead of gotos of it is going to be a spaghetti code. Enums are fine to does not care about the numbers for the defines, because they are incremented automatically if you add a new one.

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

        }
    }
}

Upvotes: 4

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143071

Your teacher meant that instead of hardcoding constants all over the place you need to declare your i as enum.

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

some_type i;

And then read up on enums.

Upvotes: 1

Related Questions