2014-03-04 74 views
0

我想知道如何從用戶中獲取enum變量「today」的enum值,而不是像給出的例子那樣初始化它。 我必須使用scanf來將字符串數組和今天=字符串數組嗎?從用戶獲取枚舉值

#include <stdio.h> 
enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday}; 
int main(){ 
enum week today; 
today=wednesday; 
printf("%d day",today+1); 
return 0; 
} 

回答

0

是或多或少。枚舉在內部用int表示,枚舉類型的名稱在編譯期間丟失。

你的程序將打印

4 day 

如果你想保留的天名字你必須有一個字符串數組如

const char *days[] = 
{ 
    "sunday", "monday", "tuesday", "wednesday", ... 
} ; 

並做轉換自己。例如:

printf ("The day is %s", days[monday]) ; 

將打印

The day is monday 
1

這是不可能與普通enum。一個經典的訣竅是用一個array of const char*來擴大枚舉,其中您按照枚舉相同的順序存儲名稱。然後,您可以使用一個枚舉值作爲數組中的索引來檢索相應的string值。

// enum to string 
printf("%s\n", week_str[MONDAY]); 
// string to enum 
const char* input = "tuesday"; // get this from scanf or something 
size_t length = strlen(input); 
int i; 
int found = -1; 
for (i = 0; i <= WEDNESDAY; i++) { 
    if(strncmp(input, week_str[i], length) == 0) { 
    found = i; 
    break; 
    } 
} 
printf("Found: %i", found); 
0

我會做這樣的:

#include <stdio.h> 
#include <ctype.h> 

enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday }; 

char * EnumToString(int day) { 
    switch (day) { 
     case sunday: return "sunday"; 
     case monday: return "monday"; 
     case tuesday: return "tuesday"; 
     case wednesday: return "wednesay"; 
     case thursday: return "thursday"; 
     case friday: default: return "friday"; 
    } 
} 

enum week StringToEnum(char * day) { 

    // To not be case sensitive 
    for(int i = 0; str[i]; i++){ 
     day[i] = tolower(day[i]); 
    } 
    switch (day) { 
     case "sunday": return sunday; 
     case "monday": return monday; 
     case "tuesday": return tuesday; 
     case "wednesday": return wednesay; 
     case "thursday": return thursday; 
     case "friday": default: return friday; 
    } 
} 

int main(){ 
    enum week today; 
    today=wednesday; 
    printf("%dth day is %s",today+1, EnumToString(today+1)); 
    return 0; 
} 

它會打印:

4th day is thursday 
+0

這我** **嚴重優化。 C標準確保'星期日'的數值是0,'星期一'的數值是1,依此類推。 –

+0

你的意思是將枚舉值替換爲函數的枚舉值?但是,如果稍後要在枚舉中添加或刪除值,則必須重新編碼整個函數。 – Lovy

+0

不,更糟糕的是,它實際上是同樣的事情,但它很容易出錯並且不易讀。看看我和pmr的回答,這就是我的意思。 –