cin一个c ++结构中的几个枚举

问题描述 投票:0回答:1

以下是我的代码

enum Color {red, blue};

enum Number {3,4};

enum Shape {circle, square};

struct article 
{

enum Color color;

enum Number number;

enum Shape shape;

}article_1;

//assume I have the below for all three enums

std::istream& operator>>( std::istream& is, Color& I ) 

{

    int tmp ;
    if ( is >> tmp )
        i = static_cast<Color>( tmp ) ;
    return is ;
}

int main ()

cout<<"Enter the Color : ";

cin>>article_1.color;

cout<<"Enter the Number : ";

cin>>article_1.number;

cout<<"Enter the Shape : ";

cin>>article_1.shape;

return 0;
}

该代码编译无任何错误。但是,当终端弹出要求我输入颜色时,当我输入红色时,终端消失,并且我收到一条错误消息,指出Program.exe已退出,代码为0(0x0)。我在做什么错?

c++ struct enums casting cin
1个回答
0
投票

enumscompile-level功能。编译应用后,就只有数字。

您将不得不使用cin字符串,并将其与runtime字符串(不是枚举)进行比较,以获取所需的内容。

std::string x;
cin >> x;
 if (x == "red") { }
© www.soinside.com 2019 - 2024. All rights reserved.