Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum type can not accept cin command

Tags:

c++

enums

Look t this code plz:

#include <iostream>
using namespace std;
int main()
{

    enum object {s,k,g};
    object o,t;

    cout << "Player One: "; cin >> o;
    cout << "Player Two: "; cin >> t;

    if (o==s && t==g) cout << "The Winner is Player One.\n";
    else if (o==k && t==s) cout << "The Winner is Player One.\n";
    else if (o==g && t==k) cout << "The Winner is Player One.\n";
    else if (o==g && t==s) cout << "The Winner is Player Two.\n";
    else if (o==s && t==k) cout << "The Winner is Player Two.\n";
    else if (o==k && t==g) cout << "The Winner is Player Two.\n";
    else cout << "No One is the Winner.\n";
        return 0;
}

while compiling I will get this error:no match for 'operator>>' in 'std::cin >> o I'm using code-blocks. so what is wrong with this code?

like image 926
Inside Man Avatar asked Dec 12 '22 03:12

Inside Man


1 Answers

There is no operator>>() for enum. You can implement one yourself:

std::istream& operator>>( std::istream& is, object& i )
{
    int tmp ;
    if ( is >> tmp )
        i = static_cast<object>( tmp ) ;
    return is ;
}

Of course, it would be easier if you just cin an integer and cast yourself. Just want to show you how to write an cin >> operator.

like image 80
Matchman Avatar answered Dec 30 '22 04:12

Matchman