enum type can not accept cin command

前端 未结 3 2134
眼角桃花
眼角桃花 2020-12-03 09:43

Look t this code plz:

#include 
using namespace std;
int main()
{

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

    cout << \"Player One:          


        
相关标签:
3条回答
  • 2020-12-03 09:45

    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.

    0 讨论(0)
  • 2020-12-03 09:47

    If you're not familiar with Operator Overloading concept and want a quick-fix, simply use:

    scanf("%d%d", &o, &t);
    
    0 讨论(0)
  • 2020-12-03 09:54

    Do you expect to be able to type "s", "k", or "g" and have it parse those into your enum type? If so, you need to define your own stream operator, like this:

    std::istream& operator>>(std::istream& is, object& obj) {
        std::string text;
        if (is >> text) {
            if (is == "s") {
                obj = s;
            }
            // TODO: else-if blocks for other values
            // TODO: else block to set the stream state to failed
        }
        return is;
    }
    
    0 讨论(0)
提交回复
热议问题