枚举类型不能接受cin命令

时间:2012-04-29 11:18:37

标签: c++ enums

看一下这段代码:

#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;
}
编译时

我会收到此错误:no match for 'operator>>' in 'std::cin >> o 我正在使用代码块。那么这段代码有什么问题呢?

3 个答案:

答案 0 :(得分:5)

枚举没有运算符&gt;&gt;()。你可以自己实现一个:

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

当然,如果你只是一个整数并自己投射会更容易。只是想告诉你如何写一个cin&gt;&gt;运营商。

答案 1 :(得分:4)

您希望能够键入“s”,“k”或“g”并将其解析为枚举类型吗?如果是这样,您需要定义自己的流运算符,如下所示:

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;
}

答案 2 :(得分:1)

如果您不熟悉运营商超载的概念并想要快速修复,只需使用:

scanf("%d%d", &o, &t);