converting from int to enum

后端 未结 4 1365
渐次进展
渐次进展 2021-01-20 08:31

I have declared the following enum :

  enum periods {one, five, ten, fifteen, thirty};

and now I want to pass it as a commandline argument

4条回答
  •  孤独总比滥情好
    2021-01-20 09:14

    I have declared the following enum :

    enum periods {one, five, ten, fifteen, thirty};
    

    and now I want to pass it as a commandline argument in my main function.

    periods mp = atoi(argv[2]);   // simplified for answer...
    

    So, there are several issues:

    • you need to cast the int returned by atoi to the enum type... static_cast(...)
    • you should realise that an argv[2] of "0" will be mapped to the enumeration identifier "one", "1" will map to "five" etc...
      • if you actually want "1" to map to "one", "5" to "five" etc., the easiest way is to change your enum: enum periods { one = 1, five = 5, ten = 10, fifteen = 15, thirty = 30 };, but your example's obviously a little contrived so it's impossible to guess what will work best for your real needs
    • there's no validation

    You're better off creating a function:

    periods to_periods(const std::string& s)
    {
        if (s == "one") return one;
        if (s == "five") return five;
        if (s == "ten") return ten;
        if (s == "fifteen") return fifteen;
        if (s == "thirty") return thirty;
        throw std::runtime_error("invalid conversion from text to periods");
    }
    

    (When there are more cases, it's not uncommon to use a std::map or sorted std::vector to track these associations, and it allows reusable algorithms and the same data to support conversions from enum numeric value to textual identifier.)

提交回复
热议问题