Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing code in enum

Tags:

c++

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;
    }
}
like image 847
kryticrecte Avatar asked Mar 11 '26 08:03

kryticrecte


2 Answers

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;

        }
    }
}
like image 88
phschoen Avatar answered Mar 12 '26 22:03

phschoen


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.

like image 31
Michael Krelin - hacker Avatar answered Mar 12 '26 21:03

Michael Krelin - hacker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!