以下是我的代码:
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 ++中,字符串和枚举之间没有智能转换。
您的输入代码无效,因为您从输入流中读取了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 };
)。这就是在整数和枚举之间进行合法转换的原因。但是在执行此操作时要非常小心,因为一旦整数与枚举器值不完全匹配,它就会变得复杂。