Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cin >> operand cannot work with enum

This is a code i did for practice. when i compile this, it wldnt allow cin >> choice to be compiled. It says "Error 2 error C2088: '>>' : illegal for class" and "Error 1 error C2371: 'choice' : redefinition; different basic types" Can i get some advise on how to solve this? much appreciated!

#include <iostream>

using namespace std;

int main()
{
    cout << "Difficulty levels\n\n";
    cout << "Easy - 0\n";
    cout << "Normal - 1\n";
    cout << "Hard - 2\n";

    enum options { Easy, Normal, Hard, Undecided };
    options choice = Undecided;
    cout << "Your choice: ";
    int choice;
    cin >> choice;

    switch (choice)
    {
    case 0:
        cout << "You picked Easy.\n";
        break;
    case 1:
        cout << "You picked Normal. \n";
        break;
    case 2:
        cout << "You picked Hard. \n";
        break;
    default:
        cout << "You made an illegal choice.\n";
    }

    return 0;
}
like image 507
user3547704 Avatar asked Jan 24 '26 02:01

user3547704


1 Answers

It says "Error 2 error C2088: '>>' : illegal for class" and "Error 1 error C2371: 'choice' : redefinition; different basic types" Can i get some advise on how to solve this?

Sure, let us see what you wrote:

...
options choice = Undecided;
// ^^^^^^^^^^^
cout << "Your choice: ";
int choice;
// ^^^^^^^^
cin >> choice;
..

This is a mistake. First, you should define the same variable only once. Second, enumerators do not have the operator>> overloaded, so you cannot use the former declaration.

The solution is to remove the former, so you would be writing this overall (with the ugly indent fixed):

main.cpp

#include <iostream>

using namespace std;

int main()
{
    enum options { Easy, Normal, Hard, Undecided };
    cout << "Difficulty levels\n\n";
    cout << "Easy - " << Easy << "\n";
    cout << "Normal - " << Normal << "\n";
    cout << "Hard - " << Hard << "\n";
    cout << "Your choice: ";
    int choice;
    cin >> choice;

    switch (choice)
    {
    case Easy:
        cout << "You picked Easy.\n";
        break;
    case Normal:
        cout << "You picked Normal.\n";
        break;
    case Hard:
        cout << "You picked Hard.\n";
        break;
    default:
        cout << "You made an illegal choice.\n";
    }

    return 0;
}

Output

g++ main.cpp && ./a.out 
Difficulty levels

Easy - 0
Normal - 1
Hard - 2
Your choice: 0
You picked Easy.
like image 134
lpapp Avatar answered Jan 25 '26 16:01

lpapp



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!