首页 > 解决方案 > 从 cin 获取 c++ 结构中多个枚举的输入

问题描述

以下是我的代码:

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 has exited with code 0(0x0)。我究竟做错了什么?

标签: c++structenumsiostreamcin

解决方案


枚举编译级别的功能。编译应用程序后,只有数字。您放入枚举中的字符串在程序运行时被数字替换。

您必须输入字符串并将其与运行时字符串(不是枚举)进行比较才能获得所需的内容。

std::string x;
cin >> x;
if (x == "red") 
{
}

您还可以创建一个std::map<std::string,int>. scohe001的评论也显示了一些方法。


推荐阅读