简体   繁体   English

如何在 C++ 中将状态输入到枚举类型的变量中?

[英]How can I input a state to a variable of enum type in C++?

#include <iostream>
enum Day { Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun };
void printa(Day day);
int main() {
    enum Day day = Sun;
    printa(day);

    return 0;
}
void printa(Day day) {
    if (day > Fri)
        std::cout << "weekend" << std::endl;
    else
        std::cout << "weekdays" << std::endl;
}

See above code.见上面的代码。

Day is defined as a variable of type enum. Day 被定义为枚举类型的变量。

The value of “Sun” is allocated to day, which is 7. “Sun”的值分配给day,即7。

So as a result, "weekend" is printed.因此,“周末”被打印出来。

Now I want this: I input a value (from 1 to 7) to day, that is, give it a state.现在我想要这个:我给day输入一个值(从1到7),也就是给它一个状态。

Here is the code:这是代码:

#include <iostream>
enum Day { Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun };
void printa(Day day);
int main() {
    enum Day day = Sun;
    std::cin >> day; // Here is the added line
    printa(day);

    return 0;
}
void printa(Day day) {
    if (day > Fri)
        std::cout << "weekend" << std::endl;
    else
        std::cout << "weekdays" << std::endl;
}

It can't work.它不能工作。

Can anybody tell me why?谁能告诉我为什么?

How can I input a state to a variable of enum type in C++ ?如何在 C++ 中将状态输入到枚举类型的变量中?

You can't use cin direct to enum type, but you can do it to an int and static cast it to your enum type like shown below:您不能将 cin 直接用于枚举类型,但您可以将其用于 int 并将其静态转换为您的枚举类型,如下所示:

#include <iostream>

enum Day : uint16_t { Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun };

void printa(Day day) {
     if (day > Fri)
        std::cout << "weekend" << std::endl;
     else
        std::cout << "weekdays" << std::endl;
}

int main() {
    uint16_t day = Sun;

    std::cin >> day;

    printa(static_cast<Day>(day));

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM