使用integer显示枚举类型的值

display values of enum type from using integer

本文关键字:类型 枚举 integer 显示 使用      更新时间:2023-10-16

我想通过使用enumType变量来获取当前状态。但有了这些代码,我无法获得值。。例如,如果enumType=3,则状态应为爬网。。。

#include <iostream>
#include <windows.h>
#include <ctime>
using namespace std;
int main()
{
    int enumType;
    srand((unsigned)time(0));
    enumType = rand()%3;
    enum state{
        stand,
        walk,
        run,
        crawl,
    };
    state currentState;
    (int)currentState =enumType;
    cout<<state.currentState;
    system("pause");
    return 0;
}

老兄。C/C++不是这样工作的:)。如果您想要"有意义的名称"(如"enum state 3"=="crawl"),那么您可以自己将枚举值映射到文本字符串。

你可以创建一个静态表,你可以使用"switch/case"块,你可以用STL映射。有很多选择,但你必须自己手动完成。它并不是自动内置到语言中的(比如C#)。

string strState;
switch(currentState)
{
   case stand:
     strState = "Stand";
   break;
   case walk:
     strState = "walk";
   break;
   case run:
     strState = "run";
   break;
   case crawl:
     strState = "crawl";
   break;
}
cout << strState;

这就是您所需要的:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include <cstdlib>
#include <ctime>

int main()
{
srand(time(0));

enum state{
    stand,
    walk,
    run,
    crawl,
};
state min=stand;
state max=crawl;
state enumType = (state)(rand()%((max-min)+1));
state currentState;
currentState =enumType;
printf("  %i  ",currentState);

return 0;
}

结果是:

11.01.02.。。。每次运行,0-2之间的值不同,因为它是"地板"新编辑:(max-min)+1)在模块化的东西