从cin获取c ++结构中几个枚举的输入

问题描述 投票:2回答:2

以下是我的代码:

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++ struct enums iostream cin
2个回答
2
投票

enumscompile-level功能。编译应用后,只有数字。程序运行时,您放入枚举的字符串将替换为数字。

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

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

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


0
投票

在C ++中,字符串和枚举之间没有智能转换。

您的输入代码无效,因为您从输入流中读取了int并将其转换为颜色:

  • 如果您输入与枚举值编码之一相对应的有效整数,则可以使用。
  • 但是如果输入字符串,由于类型不兼容,输入操作将失败。输入流出错,对该流的所有后续操作将失败,直到您清除错误标志。

如果要读取字符串,则需要注意。例如,使用以下代码:

std::istream& operator>>( std::istream& is, Color& I ) 
{
    std::string tmp;
    if ( is >> tmp ) {
        for (auto&c:tmp)
            c=std::tolower(c);  
        if (tmp=="red") I = red; 
        else if (tmp=="blue") I = blue;   
        // but what happens if the string is invalid ???
    }
    return is ;
}
std::ostream& operator<<( std::ostream& os, Color& O ) 
{
    std::string tmp; 
    switch (O) {
        case red:  tmp="red"; break; 
        case blue: tmp="blue"; break; 
        default:   tmp="oops!!";
    }
    return os<<tmp ;
} 

当然,这只是一个幼稚的例子。实际上,您可能会有一个std :: map来保存字符串和枚举之间的关联,反之亦然。

值得知道的地方:

枚举中的枚举数可以映射为整数值。默认情况下,第一个枚举数(red)映射为0。后面的枚举数的值比前面的枚举数大1(即blue为1)。

但是您可以自由设置一个值(例如enum Color { red=2, green, blue=green+4 };)。这就是在整数和枚举之间进行合法转换的原因。但是在执行此操作时要非常小心,因为一旦整数与枚举器值不完全匹配,它就会变得复杂。

© www.soinside.com 2019 - 2024. All rights reserved.