2012-07-13 67 views
-1

我想通过使用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; 
} 
+0

那么问题是什么? – 2012-07-13 05:33:56

回答

2

伙计。 C/C++不能这样工作:)。如果你想要“有意义的名字”(比如“enum state 3”==“crawl”),那么你可以自己将枚举值映射到文本字符串。

您可以创建一个静态表,你可以使用一个“开关/箱”块,你可以使用STL的地图。有很多选择 - 但你必须自己动手做。它不是自动内置到语言中(如C#)。

2
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; 
1

这是你所需要的:

#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; 
} 

和结果是:

... 每次运行,不同的0-2之间的值,因为它是 新编辑“地板”:在模事情(最大值 - 最小值)+1) 10
+0

谢谢,,,,我有一个C++任务,我想你能帮助我对,,,如果可以,请给我您的电子邮件地址。要[email protected]然后我将寄给你..请帮帮我此 – 2012-07-13 16:57:16

+1

爬网站= 3。 %3只会给你0,1或2或站立,走路和跑步。但没有3 =爬行。请修复你的错误。 – 2012-07-13 22:47:17

+0

1用于示出错误 – 2012-07-15 19:31:45