在C中使用枚舉類型的變量作為字符串的簡(jiǎn)單方法?我想做的是:typedef enum { ONE, TWO, THREE } Numbers;我正在嘗試編寫(xiě)一個(gè)函數(shù),它將執(zhí)行類似于以下情況的開(kāi)關(guān)情況:char num_str[10];int process_numbers_str(Numbers num) {
switch(num) {
case ONE:
case TWO:
case THREE:
{
strcpy(num_str, num); //some way to get the symbolic constant name in here?
} break;
default:
return 0; //no match
return 1;}與其在每一種情況下定義,是否有一種方法可以像我前面所做的那樣使用枚舉變量來(lái)設(shè)置它呢?
3 回答

郎朗坤
TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊
char*
enum
int

吃雞游戲
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
// Define your enumeration like this (in say numbers.h);ENUM_BEGIN( Numbers ) ENUM(ONE), ENUM(TWO), ENUM(FOUR)ENUM_END( Numbers )// The macros are defined in a more fundamental .h file (say defs.h);#define ENUM_BEGIN(typ) enum typ {#define ENUM(nam) nam#define ENUM_END(typ) };// Now in one and only one .c file, redefine the ENUM macros and reinclude// the numbers.h file to build a string table#undef ENUM_BEGIN#undef ENUM#undef ENUM_END#define ENUM_BEGIN(typ) const char * typ ## _name_table [] = {#define ENUM(nam) #nam#define ENUM_END(typ) };#undef NUMBERS_H_INCLUDED // whatever you need to do to enable reinclusion#include "numbers.h"// Now you can do exactly what you want to do, with no retyping, and for any// number of enumerated types defined with the ENUM macro family// Your code follows;char num_str[10];int process_numbers_str(Numbers num) { switch(num) { case ONE: case TWO: case THREE: { strcpy(num_str, Numbers_name_table[num]); // eg TWO -> "TWO" } break; default: return 0; //no match return 1;}// Sweet no ? After being frustrated by this for years, I finally came up// with this solution for my most recent project and plan to reuse the idea// forever
- 3 回答
- 0 關(guān)注
- 1088 瀏覽
添加回答
舉報(bào)
0/150
提交
取消