以下是我的代码:
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)
。我做错了什么?
最佳答案
enums是编译级功能。一旦应用程序编译完成,就只有数字了。程序运行时,您放入枚举中的字符串将被数字替换。
您必须 cin 一个字符串并将其与运行时字符串(而不是枚举)进行比较才能获得您需要的内容。
std::string x;
cin >> x;
if (x == "red")
{
}
您还可以创建 std::map<std::string,int>
。 comment by scohe001 也展示了一些方法。
关于c++ - 从 cin 获取 C++ 结构中多个枚举的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59618256/