c++ - 从 cin 获取 C++ 结构中多个枚举的输入

标签 c++ struct enums iostream cin

以下是我的代码:

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/

相关文章:

c++ - OpenCV 保存 CV_32FC1 图像

c++ - 有没有办法在 Windows 的 basic_iostream 上获得非锁定流插入/提取?

c++ - 唯一地将值插入优先级队列 C++

C# 结构的自动深拷贝

c - 有多大的结构可以有效地按值传递?

c - 使用 struct 和 stdin 在 C 中输出的问题

c++ - 使用指针和结构复制类的构造函数

Java 枚举出错?

Java 迷宫求解器

java - 将配置属性转换为枚举值