how do I use an enum value on a switch statement in C++

后端 未结 8 1279
独厮守ぢ
独厮守ぢ 2020-12-02 20:16

I would like to use an enum value for a switch statement. Is it possible to use the enum values enclosed in \"{}\" as cho

相关标签:
8条回答
  • 2020-12-02 20:44

    You can use an enumerated value just like an integer:

    myChoice c;
    
    ...
    
    switch( c ) {
    case EASY:
        DoStuff();
        break;
    case MEDIUM:
        ...
    }
    
    0 讨论(0)
  • 2020-12-02 20:49
    #include <iostream>
    using namespace std;
    
    int main() {
    
        enum level {EASY = 1, NORMAL, HARD};
    
        // Present menu
        int choice;
        cout << "Choose your level:\n\n";
        cout << "1 - Easy.\n";
        cout << "2 - Normal.\n";
        cout << "3 - Hard.\n\n";
        cout << "Choice --> ";
        cin >> choice;
        cout << endl;
    
        switch (choice) {
        case EASY:
            cout << "You chose Easy.\n";
            break;
        case NORMAL:
            cout << "You chose Normal.\n";
            break;
        case HARD:
            cout << "You chose Hard.\n";
            break;
        default:
            cout << "Invalid choice.\n";
        }
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题