问题
How can i visualize the types of food with type enum?
typedef struct cat{
int code;
int age;
float weight;
enum {kibbles,canned_food,tuna_fish}food;
} cats;
int n,i;
printf("Insert a number: ");
scanf("%d",&n);
cats *cat_arr = calloc(n, sizeof(cats));
for(i = 0;i<n;i++){
printf("Code: ");
scanf("%d",&cat_arr[i].code);
printf("Age: ");
scanf("%d",&cat_arr[i].age);
printf("weight: ");
scanf("%f",&cat_arr[i].weight);
printf("Food: ");
scanf("%d",&cat_arr[i].food);
}
for(i=0;i<n;i++){
if(cat_arr[i].age < 4 && cat_arr[i].weight > avg){
printf("%d %s",cat_arr[i].code,cat_arr[i].food); <---- HERE
}
}
I want insert type of food with numbers and display the name that i assigned with enum.
回答1:
There's no automatic way to get the string equivalent of an enum constant. You'll need to create a mapping of enums to their string equivalents and reference that.
const char *food_names[] = { "kibbles" , "canned_food" ,"tuna_fish" };
...
printf("%d %s", cat_arr[i].code, food_names[cat_arr[i].food]);
回答2:
If you want to do that in a somewhat automated way, you'll need to use some preprocessor-magic:
#define FOOD(X) \
X(kibbles), \
X(canned_food), \
X(tuna_fish)
#define EXPAND_AS_ENUM(a) a
#define EXPAND_AS_STRING(a) #a
enum
{
FOOD(EXPAND_AS_ENUM)
} food;
const char* food_names[] =
{
FOOD(EXPAND_AS_STRING)
}
This way, you'll get an enum and the corresponding string-array with matching names
回答3:
It's hard to get what you wxactly mean but if you want to get enum name from index then:
struct Type{
enum Err{
not_found = 0,
internet = 1
}
std::string get( int index ){
if(index == 0) return "not_found";
if(index == 1) return "internet";
}
};
Then call the get function with index as argument
来源:https://stackoverflow.com/questions/61344384/visualize-enum-value