c++ - 从 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)
。我究竟做错了什么?
解决方案
枚举是编译级别的功能。编译应用程序后,只有数字。您放入枚举中的字符串在程序运行时被数字替换。
您必须输入字符串并将其与运行时字符串(不是枚举)进行比较才能获得所需的内容。
std::string x;
cin >> x;
if (x == "red")
{
}
您还可以创建一个std::map<std::string,int>
. scohe001的评论也显示了一些方法。
推荐阅读
- c++ - 用最近定义的结构替换前向声明的结构
- python - 姜戈。理智和可理解的一对一关系
- maven - 将 Maven 项目 Liferay 6.2 迁移到 7.2
- google-app-engine - 如何根据 App Engine 支出限制在 Stackdriver 中发出警报?
- php - 在php中的同一屏幕上创建图像和对话框
- html - 如何在 CSS 网格设置中考虑动态行?
- python - 使用 % 给出错误来查找偶数或奇数的 Python 程序
- python - 从 json 文件中读取嵌套数据
- pytorch - 从 torchvision.datasets.vision 导入 VisionDataset ImportError:没有名为 vision 的模块
- sql - 具有Level Pseudocolumn的Dual table的内部过程