如何打印枚舉變量的內容?
#include <stdio.h>
#include <string>
using namespace std;
struct Student
{
? ? int math;
? ? int english;
};
enum myclass {
? ? chinese,
? ? english,
? ? math,
? ? PE,
? ? art,
? ? computer,
};
int main(int argc, char** argv)
{
? ? struct Student s = { 95,35 };
? ? myclass my = myclass::math;
? ? printf("?");
? ? return 0;
}
2024-01-07
枚舉變量的提出是為了方便對一組離散的值進行管理和表示,而為了正確的限定這組離散的值的范圍,就規定了枚舉變量和整數值相關聯。
一般來說,我們不會對枚舉變量的值進行打印,而是根據其值進行一些邏輯判斷,例如下面的代碼:
if (my == myclass::math) {
? ? ? ? printf("my class is math!");
????????// 處理 my 為 match 的邏輯
}
如果想打印其值的話,直接把枚舉變量看作一個整數進行打印即可:
printf("The value of my is: %d\n", my);
當 my 為 match 的時候,值應該為 2,因為是從 0 開始排序的:
enum myclass {
? ? chinese,? ? ? // 0
? ? english,? ? ? ?// 1
? ? math,? ? ?????? // 2
? ? PE,? ? ? ? ???????// 3
? ? art,? ? ? ? ????? ?// 4
? ? computer,? ? // 5
};