我記得之前有個同事有透過程式碼的撰寫
將enum的數字變數,轉成string
但是原始碼我後來忘記了
現在努力回想, 也在網路找一些資料
試圖拼湊回來
方法一
好像可以了..
#define STATE_STRLENGTH 32#define stringiz(arg) #arg //將數字前面加# 就是字串化/* enum states for the power meter */typedef enum { STATE_UNSET = 0, STATE_INIT, STATE_OPEN, STATE_PROBE, STATE_EARLYRESUME, STATE_EARLYSUSPEND, STATE_RESUME, STATE_SUSPEND, STATE_REMOVE, STATE_SHUTDOWN, STATE_CLOSE, STATE_EXIT, STATE_MAX,} Numbers;char num_str[STATE_MAX][STATE_STRLENGTH] = { stringiz(STATE_UNSET), stringiz(STATE_INIT), stringiz(STATE_OPEN), stringiz(STATE_PROBE), stringiz(STATE_EARLYRESUME), stringiz(STATE_EARLYSUSPEND), stringiz(STATE_RESUME), stringiz(STATE_SUSPEND), stringiz(STATE_REMOVE), stringiz(STATE_SHUTDOWN), stringiz(STATE_CLOSE), stringiz(STATE_EXIT),};
要用的時候
void main(){ int val = xxx; printf("%d:%s\n", val, num_str[val]);}
另外一種寫法
透過switch case來處理文字
而不是初始時就設定好文字
void state_stringiz(void) { int i; for(i = STATE_UNSET; i < STATE_MAX; i++){ switch(i) { case STATE_UNSET: strcpy(num_str[i],stringiz(STATE_UNSET)); break; case STATE_INIT: strcpy(num_str[i],stringiz(STATE_INIT)); break; case STATE_OPEN: strcpy(num_str[i],stringiz(STATE_OPEN)); break; case STATE_PROBE: strcpy(num_str[i],stringiz(STATE_PROBE)); break; case STATE_EARLYRESUME: strcpy(num_str[i],stringiz(STATE_EARLYRESUME)); break; case STATE_EARLYSUSPEND: strcpy(num_str[i],stringiz(STATE_EARLYSUSPEND)); break; case STATE_RESUME: strcpy(num_str[i],stringiz(STATE_RESUME)); break; case STATE_SUSPEND: strcpy(num_str[i],stringiz(STATE_SUSPEND)); break; case STATE_REMOVE: strcpy(num_str[i],stringiz(STATE_REMOVE)); break; case STATE_SHUTDOWN: strcpy(num_str[i],stringiz(STATE_SHUTDOWN)); break; case STATE_CLOSE: strcpy(num_str[i],stringiz(STATE_CLOSE)); break; case STATE_EXIT: strcpy(num_str[i],stringiz(STATE_EXIT)); break; default: break; //no match } }}